RedisLockController.java 2.4 KB

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