DistributedLockComponent.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package com.ydtech.components;
  2. import lombok.RequiredArgsConstructor;
  3. import org.redisson.api.RLock;
  4. import org.redisson.api.RedissonClient;
  5. import org.springframework.stereotype.Component;
  6. import java.util.concurrent.TimeUnit;
  7. import java.util.function.Supplier;
  8. /**
  9. * @description: 分布式锁封装
  10. * @author: wenks
  11. * @date: 2025/3/24 15:08
  12. **/
  13. @Component
  14. @RequiredArgsConstructor
  15. public class DistributedLockComponent {
  16. private final RedissonClient redissonClient;
  17. // 默认配置(单位:秒)
  18. private static final int DEFAULT_WAIT_TIME = 3;
  19. private static final int DEFAULT_LEASE_TIME = 30;
  20. /**
  21. * 带返回值的锁操作
  22. *
  23. * @param lockName 锁名称
  24. * @param supplier 业务逻辑
  25. * @param waitTime 获取锁等待时间
  26. * @param leaseTime 锁持有时间
  27. * @return 业务执行结果
  28. */
  29. public <T> T executeWithLock(String lockName, Supplier<T> supplier, long waitTime, long leaseTime) throws Exception {
  30. RLock lock = redissonClient.getLock(lockName);
  31. boolean isLocked = false;
  32. try {
  33. // 尝试获取锁
  34. isLocked = lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
  35. if (isLocked) {
  36. // 执行业务逻辑
  37. return supplier.get();
  38. }
  39. throw new RuntimeException("Acquire lock failed: " + lockName);
  40. } finally {
  41. if (isLocked && lock.isHeldByCurrentThread()) {
  42. lock.unlock();
  43. }
  44. }
  45. }
  46. /**
  47. * 快速失败(带默认参数)
  48. */
  49. public <T> T fastFailExecute(String lockName, Supplier<T> supplier) throws Exception {
  50. return executeWithLock(lockName, supplier, 0, DEFAULT_LEASE_TIME);
  51. }
  52. /**
  53. * 阻塞等待锁(带默认参数)
  54. */
  55. public <T> T blockingExecute(String lockName, Supplier<T> supplier) throws Exception {
  56. return executeWithLock(lockName, supplier, DEFAULT_WAIT_TIME, -1);
  57. }
  58. /**
  59. * 无返回值操作
  60. */
  61. public void executeWithLock(String lockName, Runnable runnable, long waitTime, long leaseTime) throws Exception {
  62. executeWithLock(lockName, () -> {
  63. runnable.run();
  64. return null;
  65. }, waitTime, leaseTime);
  66. }
  67. }