• redis缓存使用本地锁


    redis缓存使用本地锁可以解决单体项目缓存击穿问题

    在N个相同服务,会存在执行最多N次

     redis缓存使用本地锁代码:

    1. package com.hdb.pingmoweb.product.web;
    2. import com.alibaba.fastjson.JSON;
    3. import com.alibaba.fastjson.TypeReference;
    4. import com.hdb.pingmoweb.product.entity.CategoryEntity;
    5. import com.hdb.pingmoweb.product.service.CategoryService;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.data.redis.core.StringRedisTemplate;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.ui.Model;
    10. import org.springframework.util.StringUtils;
    11. import org.springframework.web.bind.annotation.RequestMapping;
    12. import org.springframework.web.bind.annotation.ResponseBody;
    13. import java.io.IOException;
    14. import java.util.List;
    15. @Controller
    16. public class IndexController {
    17. @Autowired
    18. private CategoryService categoryService;
    19. @Autowired
    20. private StringRedisTemplate stringRedisTemplate;
    21. @RequestMapping({"/", "/index"})
    22. public String index(Model model) throws IOException {
    23. String level1Category = stringRedisTemplate.opsForValue().get("Level1Category");
    24. List list = null;
    25. if (StringUtils.isEmpty(level1Category)) {
    26. synchronized (this) {
    27. level1Category = stringRedisTemplate.opsForValue().get("Level1Category");
    28. if (StringUtils.isEmpty(level1Category)) {
    29. System.out.println("查询数据。。。。。。。。。");
    30. list = categoryService.getLevel1Category();
    31. level1Category = JSON.toJSONString(list);
    32. stringRedisTemplate.opsForValue().set("Level1Category", level1Category);
    33. }
    34. }
    35. }
    36. if(list ==null){
    37. list = JSON.parseObject(level1Category, new TypeReference>(){});
    38. System.out.println("缓存命中。。。");
    39. }
    40. model.addAttribute("categorys", list);
    41. return "index";
    42. }
    43. @ResponseBody
    44. @RequestMapping("/hello")
    45. public String hello(Model model) {
    46. return "hello";
    47. }
    48. }

  • 相关阅读:
    Python 中调用 Java 的 JAR 包
    selenium headless 无头模式慢
    CSP-J-2016-海港
    HTML5+CSS3小实例:纯CSS实现奥运五环
    TeamTalk中对一条连接收发消息的封装。
    鸡兔同笼问题python程序怎么写
    基于nRF52840 Dongle配合Wireshark对Mesh网络抓包并解析(Nordic)
    如果线上遇到了OOM,该如何解决?
    Java学习路线图
    C# Windows多串口绑定
  • 原文地址:https://blog.csdn.net/qq_29385297/article/details/127464101