RedisCacheController.java 2.3 KB

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