RedisLockController.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package com.ruoyi.demo.controller;
  2. import com.baomidou.lock.LockInfo;
  3. import com.baomidou.lock.LockTemplate;
  4. import com.baomidou.lock.annotation.Lock4j;
  5. import com.baomidou.lock.executor.RedissonLockExecutor;
  6. import com.ruoyi.common.core.domain.AjaxResult;
  7. import io.swagger.annotations.Api;
  8. import io.swagger.annotations.ApiOperation;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.cache.annotation.Cacheable;
  12. import org.springframework.web.bind.annotation.GetMapping;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RestController;
  15. import java.time.LocalTime;
  16. /**
  17. * 测试分布式锁的样例
  18. *
  19. * @author shenxinquan
  20. */
  21. @Api(value = "测试分布式锁的样例", tags = {"测试分布式锁的样例"})
  22. @Slf4j
  23. @RestController
  24. @RequestMapping("/demo/redisLock")
  25. public class RedisLockController {
  26. @Autowired
  27. private LockTemplate lockTemplate;
  28. /**
  29. * 测试lock4j 注解
  30. */
  31. @ApiOperation("测试lock4j 注解")
  32. @Lock4j(keys = {"#key"})
  33. @GetMapping("/testLock4j")
  34. public AjaxResult<String> testLock4j(String key, String value) {
  35. System.out.println("start:" + key + ",time:" + LocalTime.now().toString());
  36. try {
  37. Thread.sleep(10000);
  38. } catch (InterruptedException e) {
  39. e.printStackTrace();
  40. }
  41. System.out.println("end :" + key + ",time:" + LocalTime.now().toString());
  42. return AjaxResult.success("操作成功", value);
  43. }
  44. /**
  45. * 测试lock4j 工具
  46. */
  47. @ApiOperation("测试lock4j 工具")
  48. @GetMapping("/testLock4jLockTemaplate")
  49. public AjaxResult<String> testLock4jLockTemaplate(String key, String value) {
  50. final LockInfo lockInfo = lockTemplate.lock(key, 30000L, 5000L, RedissonLockExecutor.class);
  51. if (null == lockInfo) {
  52. throw new RuntimeException("业务处理中,请稍后再试");
  53. }
  54. // 获取锁成功,处理业务
  55. try {
  56. try {
  57. Thread.sleep(8000);
  58. } catch (InterruptedException e) {
  59. //
  60. }
  61. System.out.println("执行简单方法1 , 当前线程:" + Thread.currentThread().getName());
  62. } finally {
  63. //释放锁
  64. lockTemplate.releaseLock(lockInfo);
  65. }
  66. //结束
  67. return AjaxResult.success("操作成功", value);
  68. }
  69. /**
  70. * 测试spring-cache注解
  71. */
  72. @ApiOperation("测试spring-cache注解")
  73. @Cacheable(value = "test", key = "#key")
  74. @GetMapping("/testCache")
  75. public AjaxResult<String> testCache(String key) {
  76. return AjaxResult.success("操作成功", key);
  77. }
  78. }