• 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. }

  • 相关阅读:
    allegro中怎样制作和添加logo
    数仓模型设计方法论
    优质笔记软件评测(二)Logseq、Obsidian、思源笔记、FlowUs
    java运算符
    javascript中的错误类型
    用floyd算法求图中任意两点最短距离(matlab)
    聊聊「低代码」的实践之路
    Java面试题02
    视频编辑服务热门问题合集
    java-php-python-ssm校园社团管理平台计算机毕业设计
  • 原文地址:https://blog.csdn.net/qq_29385297/article/details/127464101