RedisCacheController.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package com.ruoyi.demo.controller;
  2. import com.ruoyi.common.core.domain.AjaxResult;
  3. import io.swagger.annotations.Api;
  4. import io.swagger.annotations.ApiOperation;
  5. import lombok.RequiredArgsConstructor;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.cache.annotation.CacheEvict;
  8. import org.springframework.cache.annotation.CachePut;
  9. import org.springframework.cache.annotation.Cacheable;
  10. import org.springframework.web.bind.annotation.GetMapping;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. /**
  14. * spring-cache 演示案例
  15. *
  16. * @author Lion Li
  17. */
  18. // 类级别 缓存统一配置
  19. //@CacheConfig(cacheNames = "redissonCacheMap")
  20. @Api(value = "spring-cache 演示案例", tags = {"spring-cache 演示案例"})
  21. @RequiredArgsConstructor(onConstructor_ = @Autowired)
  22. @RestController
  23. @RequestMapping("/demo/cache")
  24. public class RedisCacheController {
  25. /**
  26. * 测试 @Cacheable
  27. *
  28. * 表示这个方法有了缓存的功能,方法的返回值会被缓存下来
  29. * 下一次调用该方法前,会去检查是否缓存中已经有值
  30. * 如果有就直接返回,不调用方法
  31. * 如果没有,就调用方法,然后把结果缓存起来
  32. * 这个注解「一般用在查询方法上」
  33. *
  34. * 重点说明: 缓存注解严谨与其他筛选数据功能一起使用
  35. * 例如: 数据权限注解 会造成 缓存击穿 与 数据不一致问题
  36. *
  37. * cacheNames 为配置文件内 groupId
  38. */
  39. @ApiOperation("测试 @Cacheable")
  40. @Cacheable(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
  41. @GetMapping("/test1")
  42. public AjaxResult<String> test1(String key, String value){
  43. return AjaxResult.success("操作成功", value);
  44. }
  45. /**
  46. * 测试 @CachePut
  47. *
  48. * 加了@CachePut注解的方法,会把方法的返回值put到缓存里面缓存起来,供其它地方使用
  49. * 它「通常用在新增方法上」
  50. *
  51. * cacheNames 为 配置文件内 groupId
  52. */
  53. @ApiOperation("测试 @CachePut")
  54. @CachePut(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
  55. @GetMapping("/test2")
  56. public AjaxResult<String> test2(String key, String value){
  57. return AjaxResult.success("操作成功", value);
  58. }
  59. /**
  60. * 测试 @CacheEvict
  61. *
  62. * 使用了CacheEvict注解的方法,会清空指定缓存
  63. * 「一般用在更新或者删除的方法上」
  64. *
  65. * cacheNames 为 配置文件内 groupId
  66. */
  67. @ApiOperation("测试 @CacheEvict")
  68. @CacheEvict(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
  69. @GetMapping("/test3")
  70. public AjaxResult<String> test3(String key, String value){
  71. return AjaxResult.success("操作成功", value);
  72. }
  73. }