RedisLockController.java 2.2 KB

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