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

  • 相关阅读:
    如何设计一个mysql的统计分析表?
    重学Git:要想熟练掌握 Git 的使用,必须要先认识工作区和暂存区
    MySQL高级SQL语句(二)
    【K8s】初识PV和PVC
    三分钟,我让搞后端的学弟爱上了Eolink
    多线程和多进程的区别与联系
    常见非甾体抗炎药及作用机理
    MySQL——基础知识
    代码随想录算法训练营第四十一天 | 01背包问题 二维
    Greedy algorithm
  • 原文地址:https://blog.csdn.net/qq_29385297/article/details/127464101