配置
新建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;
}
修改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")
先请求deleteAll删除所有缓存
新增order数据
访问/order地址
第一次由于没有缓存,会进入接口查询
后面继续刷新页面,不会再进入后端接口了
|
请发表评论