使用nginx+lua脚本读写redis缓存

配置

新建spring boot项目增加redis配置

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

在需要缓存的地方增加redis缓存

package com.example.sharding.service;

import com.alibaba.fastjson.JSON;
import com.example.sharding.entity.Order;
import com.example.sharding.mapper.OrderMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public Object findAll() throws IOException {
        List<Order> orders = orderMapper.selectAll();
        ObjectMapper mapper = new ObjectMapper();
        redisTemplate.opsForValue().set("orders",mapper.writeValueAsString(orders));
        return orders;
    }

    public void save(Order order) {
        orderMapper.insert(order);
        redisTemplate.opsForHash().put("order",order.getOrderId().toString(), JSON.parseObject(JSON.toJSONString(order)).toJSONString());
    }

    public void deleteAll() {
        orderMapper.deleteAll();
        redisTemplate.delete("order");
        redisTemplate.delete("orders");
    }
}

修改example.conf

server {
    listen       80;  
    server_name  _;  
  
    location = /order {  
	    default_type 'text/html';  
	    lua_code_cache off;  
	    content_by_lua_file C:\work\openresty-1.13.6.1-win32\example\lua/test_redis_basic.lua;  
	}

    location /lua {
        default_type 'text/html';  
        lua_code_cache off;  
        content_by_lua_file C:\work\openresty-1.13.6.1-win32\example\lua/test.lua;  
    }

    # 其他请求回源到tomcat
    location / {  
    	proxy_pass http://tomcat/; 
	}  

}

# 后端服务地址
upstream tomcat {  
    server 127.0.0.1:8080 max_fails=5 fail_timeout=10s weight=1; 
    keepalive 100;  
}  

修改test_redis_basic.lua文件

local function close_redis(red)  
    if not red then  
        return  
    end  
    local ok, err = red:close()  
    if not ok then  
        ngx.say("close redis error : ", err)  
    end  
end  


local function read_order()  
    local resp = ngx.location.capture("/order/query", {  
        method = ngx.HTTP_GET
    })  
    if not resp then  
        return  
    end  
    if resp.status ~= 200 then   
        return  
    end  
    return resp.body  
end  

  
local redis = require("resty.redis")  
local cjson = require("cjson")  -- 引入json模块
  
--创建实例  
local red = redis:new()  
--设置超时(毫秒)  
red:set_timeout(1000)  
--建立连接  
local ip = "127.0.0.1"  
local port = 6379  
local ok, err = red:connect(ip, port)  
if not ok then  
    ngx.say("connect to redis error : ", err)  
    return close_redis(red)  
end 

local res, err = red:auth("shiyuesoft")
if not res then
    ngx.say("failed to authenticate: ", err)
    return
end
  
--调用API获取数据  
local resp, err = red:get("orders")
if not resp then  
    ngx.say("get msg error : ", err)  
    return close_redis(red)  
end  
--得到的数据为空处理  
if resp == ngx.null then  
    resp = read_order()  --回源到tomcat去查询
end  
ngx.say(cjson.decode(resp))  --对返回的数据转换成json对象
  
close_redis(red)  

先请求deleteAll删除所有缓存

新增order数据

访问/order地址

第一次由于没有缓存,会进入接口查询

后面继续刷新页面,不会再进入后端接口了

posted @ 2018-04-29 15:54  rianbowymail  阅读(164)  评论(0编辑  收藏  举报