RedisLockController.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.ruoyi.demo.controller;
  2. import com.ruoyi.common.annotation.RedisLock;
  3. import com.ruoyi.common.core.domain.AjaxResult;
  4. import com.ruoyi.common.core.redis.RedisLockManager;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.beans.factory.annotation.Autowired;
  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. import java.util.concurrent.TimeUnit;
  12. /**
  13. * 测试分布式锁的样例
  14. *
  15. * @author shenxinquan
  16. */
  17. @Slf4j
  18. @RestController
  19. @RequestMapping("/demo/redisLock")
  20. public class RedisLockController {
  21. @Autowired
  22. private RedisLockManager redisLockManager;
  23. /**
  24. * #p0 标识取第一个参数为redis锁的key
  25. */
  26. @GetMapping("/testLock1")
  27. @RedisLock(expireTime = 10, key = "#p0")
  28. public AjaxResult<String> testLock1(String key, String value) {
  29. try {
  30. // 同时请求排队
  31. // Thread.sleep(5000);
  32. // 锁超时测试
  33. Thread.sleep(11000);
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. return AjaxResult.success("操作成功",value);
  38. }
  39. /**
  40. * 测试锁工具类
  41. */
  42. @GetMapping("/testLock2")
  43. public AjaxResult<Void> testLock(String key, Long time) {
  44. try {
  45. boolean flag = redisLockManager.getLock(key, time, TimeUnit.SECONDS);
  46. if (flag) {
  47. log.info("获取锁成功: " + key);
  48. Thread.sleep(3000);
  49. redisLockManager.unLock(key);
  50. log.info("释放锁成功: " + key);
  51. } else {
  52. log.error("获取锁失败: " + key);
  53. }
  54. } catch (InterruptedException e) {
  55. log.error(e.getMessage());
  56. }
  57. return AjaxResult.success();
  58. }
  59. /**
  60. * 测试spring-cache注解
  61. */
  62. @Cacheable(value = "test", key = "#key")
  63. @GetMapping("/testCache")
  64. public AjaxResult<String> testCache(String key) {
  65. return AjaxResult.success("操作成功", key);
  66. }
  67. }