# 分布式锁 Spring Boot Starter **Repository Path**: fairyTrace/distributed-lock-spring-boot-starter ## Basic Information - **Project Name**: 分布式锁 Spring Boot Starter - **Description**: 基于 Spring Boot 的分布式锁 distributed-lock-spring-boot-starter - **Primary Language**: Unknown - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-09-16 - **Last Updated**: 2025-10-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 分布式锁 #### 介绍 基于 Spring Boot 的分布式锁 distributed-lock-spring-boot-starter #### 软件架构 这个分布式锁 Starter 具有以下高质量特性: 1. **多实现支持**:Redis、Zookeeper、本地锁 2. **注解驱动**:基于注解的声明式锁 3. **SpEL支持**:灵活的锁键表达式 4. **自动配置**:开箱即用,合理默认值 5. **条件装配**:按需加载实现 6. **异常处理**:完善的异常体系和重试机制 7. **配置丰富**:支持多种配置选项 8. **线程安全**:正确的资源清理 9. **可扩展性**:易于添加新的锁实现 10. **监控友好**:支持链路追踪和监控 这个 Starter 可以直接用于生产环境,提供了企业级分布式锁解决方案。 #### 条件装配 1. 通过 ```@ConditionalOnProperty ``` 注解根据配置属性开启条件装配,如``` @ConditionalOnProperty(prefix = "distributed.lock", name = "enabled", havingValue = "true", matchIfMissing = true) ```。 2. 通过 ```@EnableConfigurationProperties(LockProperties.class)``` 注解开启配置属性的自动绑定。 3. 通过 ```@ConditionalOnClass``` 注解根据类是否存在开启条件装配,如``` @ConditionalOnClass(RedisTemplate.class) ```。 4. 通过 ```@ConditionalOnMissingBean``` 注解根据 Bean 是否存在开启条件装配,如``` @ConditionalOnMissingBean(name = "localLockExecutor") ```。 #### 使用说明 ##### 依赖导入 starter 依赖 ```xml org.fairy distributed-lock-spring-boot-starter 1.0-SNAPSHOT ``` 默认使用内存锁 ,如果需要使用redis和zookeeper,需要添加以下依赖 ```xml org.springframework.boot spring-boot-starter-data-redis org.apache.curator curator-recipes 5.4.0 ``` ##### 分布式锁配置属性: ```yaml distributed: lock: enabled: true # 开启分布式锁 default-wait-time: 5s # 分布式锁默认等待时间 default-lease-time: 30s # 分布式锁默认租约时间 redis: password: host: 129.204.157.194 # redis 主机地址 port: 16379 # redis 端口 max-idle: 10 # redis 连接池最大空闲连接数 min-idle: 1 # redis 连接池最小空闲连接数 max-wait: 5s # redis 连接池最大等待时间 pool-enabled: true # redis 连接池是否开启 max-total: 100 # redis 连接池最大连接数 enabled: false # 开启 redis 分布式锁 zookeeper: address: localhost:2181 # zookeeper 地址 session-timeout: 5000 # zookeeper 会话超时时间 connection-timeout: 5000 # zookeeper 连接超时时间 namespace: /lock # zookeeper 命名空间 enabled: false # 开启 zookeeper 分布式锁 auth: zk # zookeeper 认证方式 base-sleep-time: 1000 # zookeeper重试基础等待时间 max-retries: 3 # zookeeper重试最大次数 max-sleep-time: 1000 # zookeeper重试最大等待时间 ``` #### 注解使用示例 ```java @DistributedLock( key = "'order:' + #orderId", lockType = LockType.REDIS, waitTime = 3, leaseTime = 20000, reTryCount = 3, message = "订单处理中,请稍后重试" ) public String processOrder(String orderId, String userId) { try { // 模拟业务处理时间 Thread.sleep(1000); return String.format("订单 %s 处理成功,用户: %s", orderId, userId); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("订单处理被中断"); } } @DistributedLock(key = "'user_orders:' + #userId",waitTime = 3, leaseTime = 2000, reTryCount = 0, message = "获取订单失败") public String getUserOrders(String userId) { return String.format("用户 %s 的订单列表", userId); } ``` ##### zookeeper 锁使用示例 ```java // 基本使用 @DistributedLock( key = "'order:' + #orderId", lockType = LockType.ZOOKEEPER, waitTime = 10, timeUnit = TimeUnit.SECONDS ) public String processOrder(String orderId) { // 业务逻辑 return "Order processed: " + orderId; } // 读锁示例 @DistributedLock( key = "'config:' + #configKey + '/read'", lockType = LockType.ZOOKEEPER ) public String readConfig(String configKey) { // 读取配置,允许多个读锁 return "Config value for: " + configKey; } // 写锁示例 @DistributedLock( key = "'config:' + #configKey + '/write'", lockType = LockType.ZOOKEEPER, waitTime = 5 ) public String updateConfig(String configKey, String value) { // 更新配置,只允许一个写锁 return "Config updated: " + configKey + "=" + value; } // 信号量锁示例 @DistributedLock( key = "'semaphore:resource'", lockType = LockType.ZOOKEEPER ) public String accessResource() { // 限制资源并发访问 return "Resource accessed"; } ``` #### 编程式使用示例 ```java @Service public class InventoryService { private final LockExecutor lockExecutor; public InventoryService(LockExecutor localLockExecutor) { this.lockExecutor = localLockExecutor; } public String updateInventory(String productId, int quantity) { DistributedLock lock = lockExecutor.getLock("inventory:" + productId, 3000, 10000); try { if (lock.tryLock()) { // 模拟库存更新操作 Thread.sleep(500); return String.format("产品 %s 库存更新成功,数量: %d", productId, quantity); } else { return "获取锁失败,请重试"; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); return "操作被中断"; } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); } } } } ```