redis缓存使用本地锁可以解决单体项目缓存击穿问题
在N个相同服务,会存在执行最多N次
redis缓存使用本地锁代码:
- package com.hdb.pingmoweb.product.web;
-
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.TypeReference;
- import com.hdb.pingmoweb.product.entity.CategoryEntity;
- import com.hdb.pingmoweb.product.service.CategoryService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.util.StringUtils;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import java.io.IOException;
- import java.util.List;
-
- @Controller
- public class IndexController {
-
- @Autowired
- private CategoryService categoryService;
-
- @Autowired
- private StringRedisTemplate stringRedisTemplate;
-
- @RequestMapping({"/", "/index"})
- public String index(Model model) throws IOException {
- String level1Category = stringRedisTemplate.opsForValue().get("Level1Category");
- List
list = null; - if (StringUtils.isEmpty(level1Category)) {
- synchronized (this) {
- level1Category = stringRedisTemplate.opsForValue().get("Level1Category");
- if (StringUtils.isEmpty(level1Category)) {
- System.out.println("查询数据。。。。。。。。。");
- list = categoryService.getLevel1Category();
- level1Category = JSON.toJSONString(list);
- stringRedisTemplate.opsForValue().set("Level1Category", level1Category);
- }
- }
- }
- if(list ==null){
- list = JSON.parseObject(level1Category, new TypeReference
>(){});
- System.out.println("缓存命中。。。");
- }
- model.addAttribute("categorys", list);
- return "index";
- }
-
- @ResponseBody
- @RequestMapping("/hello")
- public String hello(Model model) {
- return "hello";
- }
- }