76 lines
1.9 KiB
Java
Raw Normal View History

2021-06-04 16:09:43 +08:00
package com.ruoyi.demo.controller;
import com.ruoyi.common.annotation.RedisLock;
import com.ruoyi.common.core.domain.AjaxResult;
2021-06-09 23:31:47 +08:00
import com.ruoyi.common.core.redis.RedisLockManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
2021-06-10 20:23:15 +08:00
import org.springframework.cache.annotation.Cacheable;
2021-06-04 16:09:43 +08:00
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
2021-06-09 23:31:47 +08:00
import java.util.concurrent.TimeUnit;
2021-06-04 16:09:43 +08:00
/**
* 测试分布式锁的样例
*
* @author shenxinquan
*/
2021-06-09 23:31:47 +08:00
@Slf4j
2021-06-04 16:09:43 +08:00
@RestController
@RequestMapping("/demo/redisLock")
public class RedisLockController {
2021-06-09 23:31:47 +08:00
@Autowired
private RedisLockManager redisLockManager;
2021-06-04 16:09:43 +08:00
/**
* #p0 标识取第一个参数为redis锁的key
*/
2021-06-09 23:31:47 +08:00
@GetMapping("/testLock1")
2021-06-04 16:09:43 +08:00
@RedisLock(expireTime = 10, key = "#p0")
2021-06-09 23:31:47 +08:00
public AjaxResult<String> testLock1(String key, String value) {
2021-06-04 16:09:43 +08:00
try {
// 同时请求排队
// Thread.sleep(5000);
// 锁超时测试
Thread.sleep(11000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return AjaxResult.success("操作成功",value);
}
2021-06-09 23:31:47 +08:00
/**
* 测试锁工具类
*/
@GetMapping("/testLock2")
public AjaxResult<Void> testLock(String key, Long time) {
try {
boolean flag = redisLockManager.getLock(key, time, TimeUnit.SECONDS);
if (flag) {
log.info("获取锁成功: " + key);
Thread.sleep(3000);
redisLockManager.unLock(key);
2021-06-09 23:31:47 +08:00
log.info("释放锁成功: " + key);
} else {
log.error("获取锁失败: " + key);
}
} catch (InterruptedException e) {
log.error(e.getMessage());
}
return AjaxResult.success();
}
2021-06-10 20:23:15 +08:00
/**
* 测试spring-cache注解
*/
@Cacheable(value = "test", key = "#key")
@GetMapping("/testCache")
public AjaxResult<String> testCache(String key) {
return AjaxResult.success("操作成功", key);
}
2021-06-04 16:09:43 +08:00
}