RedisLockRegistry https://www.jianshu.com/p/8373d1e9f7a7
ZookeeperLockRegistry 通过zookeeper创建和删除有序临时节点实现 https://www.jianshu.com/p/da6ef8031eb6(暂时没有更好的原理文章)
使用实例(RedisLockRegistry、ZookeeperLockRegistry 可独立使用,本文为方便才放在一起):
1.首先引入依赖
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-zookeeper</artifactId> </dependency> <dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-redis</artifactId> </dependency></pre>
2.配置bean
@Configuration public class RedisLockConfiguration {
@Bean
public RedisLockRegistry redisLockRegistry(
RedisConnectionFactory redisConnectionFactory
) {
// 注意这里的时间单位是毫秒
return new RedisLockRegistry(redisConnectionFactory, "redis_lock_ledger", 1000 * 40L);
} }
@Configuration public class ZookeeperLockConfiguration {
@Value("${spring.elasticjob.zookeeper.server-lists}")
private String url;
@Bean
public ZookeeperLockRegistry zookeeperLockRegistry() { // 重试策略,重试时间1s,重试10次
RetryPolicy policy = new ExponentialBackoffRetry(1000, 10); // 通过工厂创建 Curator CuratorFramework newClient = CuratorFrameworkFactory.newClient(url, policy);
newClient.start();
// 注意这里的时间单位是毫秒
return new ZookeeperLockRegistry(newClient);
} }
3.使用锁
注入bean
使用ZookeeperLockRegistry: Lock lock = zookeeperLockRegistry.obtain(key);
使用RedisLockRegistry: Lock lock = redisLockRegistry.obtain(key); </pre>
Lock lock = null;
try {
....
// 指定key
lock = zookeeperLockRegistry.obtain(key);
// lock = redisLockRegistry.obtain(key);
// 尝试获取锁 getLock = lock.tryLock(1, TimeUnit.SECONDS);
if (!getLock) {
log.info("获取分布式锁超时{}", key);
return;
}
// 获取分布式锁成功、开始执行业务代码
。。。。业务代码。。。。 } catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 释放放锁
if (getLock) {
lock.unlock();
}
}