Skip to content

Lock Plugin

对应模块: io.gitee.lcgyl:lcgyl-lock-plugin

分布式锁增强插件,提供声明式和编程式的分布式锁能力。

✨ 特性

  • 多实现支持 - 支持 Redis (Redisson), Zookeeper, Database 等多种后端
  • 声明式锁 - @Lock(name = "key", waitTime = 5) 注解驱动
  • 看门狗机制 - 自动续期,防止业务未完成锁过期
  • 锁降级 - 获取锁失败时支持执行降级逻辑

🚀 快速开始

依赖引入

gradle
implementation 'io.gitee.lcgyl:lcgyl-lock-plugin:2.2.0'

配置

yaml
lcgyl:
  lock:
    type: redis  # redis, zookeeper, database
    redis:
      address: redis://localhost:6379
    default-wait-time: 5s
    default-lease-time: 30s

声明式使用(推荐)

java
@Service
public class OrderService {
    
    // 基于 SpEL 表达式的动态锁 Key
    @Lock(name = "'order:' + #orderId", waitTime = 5, timeUnit = TimeUnit.SECONDS)
    public void processOrder(String orderId) {
        // 获取锁成功,执行业务逻辑
        // 方法执行完毕自动释放锁
    }
    
    // 获取锁失败时降级处理
    @Lock(name = "'stock:' + #productId", fallback = "handleLockFailed")
    public void deductStock(String productId, int quantity) {
        stockRepository.deduct(productId, quantity);
    }
    
    public void handleLockFailed(String productId, int quantity) {
        // 降级逻辑:发送消息到队列稍后重试
        messageQueue.send("stock-retry", new StockDeductMessage(productId, quantity));
    }
}

编程式使用

java
@Service
public class InventoryService {
    
    @Inject
    private DistributedLock distributedLock;
    
    public void updateInventory(String sku, int delta) {
        String lockKey = "inventory:" + sku;
        
        try {
            // 尝试获取锁,最多等待 5 秒
            if (distributedLock.tryLock(lockKey, 5, TimeUnit.SECONDS)) {
                try {
                    // 执行业务
                    inventoryRepo.updateQuantity(sku, delta);
                } finally {
                    distributedLock.unlock(lockKey);
                }
            } else {
                throw new BusinessException("获取锁失败,请稍后重试");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new BusinessException("操作被中断");
        }
    }
}

Released under the Apache License 2.0