疯狂的狮子li
2021-11-03 5b3c390e087029b965766628a85ed0196df72a9d
ruoyi-demo/src/main/java/com/ruoyi/demo/controller/RedisCacheController.java
@@ -1,6 +1,9 @@
package com.ruoyi.demo.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
@@ -10,6 +13,8 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
/**
 * spring-cache 演示案例
 *
@@ -17,6 +22,7 @@
 */
// 类级别 缓存统一配置
//@CacheConfig(cacheNames = "redissonCacheMap")
@Api(value = "spring-cache 演示案例", tags = {"spring-cache 演示案例"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/demo/cache")
@@ -31,8 +37,12 @@
    * 如果没有,就调用方法,然后把结果缓存起来
    * 这个注解「一般用在查询方法上」
    *
    * 重点说明: 缓存注解严谨与其他筛选数据功能一起使用
    * 例如: 数据权限注解 会造成 缓存击穿 与 数据不一致问题
    *
    * cacheNames 为配置文件内 groupId
    */
   @ApiOperation("测试 @Cacheable")
   @Cacheable(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
   @GetMapping("/test1")
   public AjaxResult<String> test1(String key, String value){
@@ -47,6 +57,7 @@
    *
    * cacheNames 为 配置文件内 groupId
    */
   @ApiOperation("测试 @CachePut")
   @CachePut(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
   @GetMapping("/test2")
   public AjaxResult<String> test2(String key, String value){
@@ -61,10 +72,31 @@
    *
    * cacheNames 为 配置文件内 groupId
    */
   @ApiOperation("测试 @CacheEvict")
   @CacheEvict(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
   @GetMapping("/test3")
   public AjaxResult<String> test3(String key, String value){
      return AjaxResult.success("操作成功", value);
   }
   /**
    * 测试设置过期时间
    * 手动设置过期时间10秒
    * 11秒后获取 判断是否相等
    */
   @ApiOperation("测试设置过期时间")
   @GetMapping("/test6")
   public AjaxResult<Boolean> test6(String key, String value){
      RedisUtils.setCacheObject(key, value);
      boolean flag = RedisUtils.expire(key, 10, TimeUnit.SECONDS);
      System.out.println("***********" + flag);
      try {
         Thread.sleep(11 * 1000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
      Object obj = RedisUtils.getCacheObject(key);
      return AjaxResult.success("操作成功", value.equals(obj));
   }
}