三层缓存架构:
分布式redis缓存:
本地热点缓存:
nginx缓存:
springboot 使用thymeleaf 完成页面缓存
页面缓存实现: 对于变化不太频繁的页面,将其利用thymeleaf手动编译后,将编译好的html以string类型在redis中进行缓存。再通过responsebooy以及XXXmapper(value = “/index”,produces = “text/html;charset=utf-8”)指定按照html进行解析
实现:
依赖:redis、thymeleaf
注入:
@Autowired
private ThymeleafViewResolver thymeleafViewResolver;
controller:
@GetMapping(value = "/index",produces = "text/html;charset=utf-8")
@ResponseBody
public String index(Model model, HttpServletResponse response, HttpServletRequest request) {
String indexhtml = redisTemplate.opsForValue().get("indexhtml");
if (StringUtils.isEmpty(indexhtml)){
// 先查缓存 redis 有没有
List<Type> types1 = null;
types1 = (List<Type>) iCacheService.getCommonCache("types");
//本地缓存为空
if (types1==null || types1.isEmpty()){
String types = redisTemplate.opsForValue().get("types");
// 如果为空从数据库查询
if (StringUtils.isEmpty(types)){
//如果没有缓存查数据库
types1 = typeService.list();
if (types1 != null && !types1.isEmpty()){
// list 对象转 json
String s = JSON.toJSONString(types1);
redisTemplate.opsForValue().set("types",s);
iCacheService.setCommonCache("types",types1);
model.addAttribute("types",types1);
}
}else {
// 有缓存
types1 = (List<Type>) JSON.parse(types);
iCacheService.setCommonCache("types",types1);
//查询水果类型
model.addAttribute("types",types1);
}
}
//查询商品
List<Products> all =null;
String goodsRedis = redisTemplate.opsForValue().get("goods");
if (StringUtils.isEmpty(goodsRedis)){
all = productsService.findAll();
String s = JSON.toJSONString(all);
redisTemplate.opsForValue().set("goods",s);
}else {
all = JSONArray.parseArray(goodsRedis, Products.class);
}
model.addAttribute("goods",all);
//轮播图
List<Picture2> pictureList = picture2Service.list();
model.addAttribute("picture",pictureList);
// 无法导入SpringWebContext的包
IWebContext context = new WebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap());
indexhtml = thymeleafViewResolver.getTemplateEngine().process("index",context);
//3.将手动渲染后的html存入redis缓存
if(!StringUtils.isEmpty(indexhtml)){
redisTemplate.opsForValue().set("indexhtml",indexhtml);
redisTemplate.expire("g00list", Duration.ofSeconds(60));
}
}
return indexhtml;
}
步骤:
1.查redise有没有相关缓存
2.若没有调用数据库进行查询
查询后给request域赋值时要注意使用后model赋值
3.手动渲染html 柱状model and views模型
IWebContext context = new WebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap()); indexhtml = thymeleafViewResolver.getTemplateEngine().process("index",context);
4.放进redis中进行缓存。
设置过期时间