Java开发中的分布式锁使用教程
1. 基于ZooKeeper的分布式锁
1.1 引入依赖
在项目的pom.xml
文件中添加以下依赖:
<dependency><groupId>org.apache.curator</groupId><artifactId>curator-framework</artifactId><version>latest</version>
</dependency>
<dependency><groupId>org.apache.curator</groupId><artifactId>curator-recipes</artifactId><version>latest</version>
</dependency>
<dependency><groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId><version>latest</version>
</dependency>
1.2 配置ZooKeeper连接
在application.yml
中添加ZooKeeper连接配置:
spring:zookeeper:connect-string: localhost:2181namespace: demo
1.3 编写分布式锁实现类
@Component
public class DistributedLock {@Autowiredprivate CuratorFramework curatorFramework;public InterProcessMutex acquire(String lockPath, long waitTime, long leaseTime, TimeUnit timeUnit) throws Exception {InterProcessMutex lock = new InterProcessMutex(curatorFramework, lockPath);if (!lock.acquire(waitTime, timeUnit)) {throw new RuntimeException("获取分布式锁失败");}if (leaseTime > 0) {lock.acquire(leaseTime, timeUnit);}return lock;}public void release(InterProcessMutex lock) throws Exception {if (lock != null) {lock.release();}}
}
2. 基于Redis的分布式锁
2.1 添加Redisson依赖
在pom.xml
中添加如下配置:
<dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.20.0</version>
</dependency>
2.2 配置Redisson连接
在Spring Boot项目的配置文件application.yml
中添加Redisson配置:
spring:data:redis:host: localhostport: 6379database: 0redisson:codec: org.redisson.codec.JsonJacksonCodecsingle-server-config:address: "redis://${spring.data.redis.host}:${spring.redis.port}"database: "${spring.data.redis.database}"password: "${spring.data.redis.password}"
2.3 编写分布式锁代码类
import jakarta.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;@Service
public class RedissonLockService {@Resourceprivate Redisson redisson;public boolean tryLock(String key, long timeout, TimeUnit unit) {RLock lock = redisson.getLock(key);try {return lock.tryLock(timeout, unit);} catch (InterruptedException e) {Thread.currentThread().interrupt();return false;}}
}
3. 注意事项
- ZooKeeper锁:利用临时节点与watch机制,每个锁占用一个普通节点/lock,当需要获取锁时在/lock目录下创建一个临时节点,创建成功则表示获取锁成功,失败则watch/lock节点,有删除操作后再去争锁。
- Redisson锁:提供了原生的分布式锁实现,支持锁的自动续期和高性能,适合高并发场景。
以上是Java开发中分布式锁的基本使用教程,可以根据实际项目需求选择合适的实现方式。
AI独立开发变现实战营
点击看详情