浅谈Java(SpringBoot)基于zookeeper的分布式锁实现

通过zookeeper实现分布式锁

1、创建zookeeper的client

首先通过CuratorFrameworkFactory创建一个连接zookeeper的连接CuratorFramework client

public class CuratorFactoryBean implements FactoryBean<CuratorFramework>, InitializingBean, DisposableBean {
private static final Logger LOGGER = LoggerFactory.getLogger(ContractFileInfoController.class);
private String connectionString;
private int sessionTimeoutMs;
private int connectionTimeoutMs;
private RetryPolicy retryPolicy;
private CuratorFramework client;
public CuratorFactoryBean(String connectionString) {
this(connectionString, 500, 500);
}
public CuratorFactoryBean(String connectionString, int sessionTimeoutMs, int connectionTimeoutMs) {
this.connectionString = connectionString;
this.sessionTimeoutMs = sessionTimeoutMs;
this.connectionTimeoutMs = connectionTimeoutMs;
}
@Override
public void destroy() throws Exception {
LOGGER.info("Closing curator framework...");
this.client.close();
LOGGER.info("Closed curator framework.");
}
@Override
public CuratorFramework getObject() throws Exception {
return this.client;
}
@Override
public Class<?> getObjectType() {
return this.client != null ? this.client.getClass() : CuratorFramework.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
if (StringUtils.isEmpty(this.connectionString)) {
throw new IllegalStateException("connectionString can not be empty.");
} else {
if (this.retryPolicy == null) {
this.retryPolicy = new ExponentialBackoffRetry(1000, 2147483647, 180000);
}
this.client = CuratorFrameworkFactory.newClient(this.connectionString, this.sessionTimeoutMs, this.connectionTimeoutMs, this.retryPolicy);
this.client.start();
this.client.blockUntilConnected(30, TimeUnit.MILLISECONDS);
}
}
public void setConnectionString(String connectionString) {
this.connectionString = connectionString;
}
public void setSessionTimeoutMs(int sessionTimeoutMs) {
this.sessionTimeoutMs = sessionTimeoutMs;
}
public void setConnectionTimeoutMs(int connectionTimeoutMs) {
this.connectionTimeoutMs = connectionTimeoutMs;
}
public void setRetryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
}
public void setClient(CuratorFramework client) {
this.client = client;
}
}

2、封装分布式锁

根据CuratorFramework创建InterProcessMutex(分布式可重入排它锁)对一行数据进行上锁

public` `InterProcessMutex(CuratorFramework client, String path) {`
this``(client, path,` `new` `StandardLockInternalsDriver());`

使用 acquire方法
1、acquire() :入参为空,调用该方法后,会一直堵塞,直到抢夺到锁资源,或者zookeeper连接中断后,上抛异常。
2、acquire(long time, TimeUnit unit):入参传入超时时间、单位,抢夺时,如果出现堵塞,会在超过该时间后,返回false。


public void acquire() throws Exception {
if (!this.internalLock(-1L, (TimeUnit)null)) {
throw new IOException("Lost connection while trying to acquire lock: " + this.basePath);
}
}
public boolean acquire(long time, TimeUnit unit) throws Exception {
return this.internalLock(time, unit);
}

释放锁 mutex.release();

public void release() throws Exception {
Thread currentThread = Thread.currentThread();
InterProcessMutex.LockData lockData = (InterProcessMutex.LockData)this.threadData.get(currentThread);
if (lockData == null) {
throw new IllegalMonitorStateException("You do not own the lock: " + this.basePath);
} else {
int newLockCount = lockData.lockCount.decrementAndGet();
if (newLockCount <= 0) {
if (newLockCount < 0) {
throw new IllegalMonitorStateException("Lock count has gone negative for lock: " + this.basePath);
} else {
try {
this.internals.releaseLock(lockData.lockPath);
} finally {
this.threadData.remove(currentThread);
}
}
}
}
}

封装后的DLock代码
1、调用InterProcessMutex processMutex = dLock.mutex(path);

2、手动释放锁processMutex.release();

3、需要手动删除路径dLock.del(path);

推荐 使用:
都是 函数式编程
在业务代码执行完毕后 会释放锁和删除path
1、这个有返回结果
public T mutex(String path, ZkLockCallback zkLockCallback, long time, TimeUnit timeUnit)
2、这个无返回结果
public void mutex(String path, ZkVoidCallBack zkLockCallback, long time, TimeUnit timeUnit)

public class DLock {
 private final Logger logger;
 private static final long TIMEOUT_D = 100L;
 private static final String ROOT_PATH_D = "/dLock";
 private String lockRootPath;
 private CuratorFramework client;
 
 public DLock(CuratorFramework client) {
  this("/dLock", client);
 }
 
 public DLock(String lockRootPath, CuratorFramework client) {
  this.logger = LoggerFactory.getLogger(DLock.class);
  this.lockRootPath = lockRootPath;
  this.client = client;
 }
 public InterProcessMutex mutex(String path) {
  if (!StringUtils.startsWith(path, "/")) {
   path = Constant.keyBuilder(new Object[]{"/", path});
  }
 
  return new InterProcessMutex(this.client, Constant.keyBuilder(new Object[]{this.lockRootPath, "", path}));
 }
 
 public <T> T mutex(String path, ZkLockCallback<T> zkLockCallback) throws ZkLockException {
  return this.mutex(path, zkLockCallback, 100L, TimeUnit.MILLISECONDS);
 }
 
 public <T> T mutex(String path, ZkLockCallback<T> zkLockCallback, long time, TimeUnit timeUnit) throws ZkLockException {
  String finalPath = this.getLockPath(path);
  InterProcessMutex mutex = new InterProcessMutex(this.client, finalPath);
 
  try {
   if (!mutex.acquire(time, timeUnit)) {
    throw new ZkLockException("acquire zk lock return false");
   }
  } catch (Exception var13) {
   throw new ZkLockException("acquire zk lock failed.", var13);
  }
 
  T var8;
  try {
   var8 = zkLockCallback.doInLock();
  } finally {
   this.releaseLock(finalPath, mutex);
  }
 
  return var8;
 }
 
 private void releaseLock(String finalPath, InterProcessMutex mutex) {
  try {
   mutex.release();
   this.logger.info("delete zk node path:{}", finalPath);
   this.deleteInternal(finalPath);
  } catch (Exception var4) {
   this.logger.error("dlock", "release lock failed, path:{}", finalPath, var4);
//   LogUtil.error(this.logger, "dlock", "release lock failed, path:{}", new Object[]{finalPath, var4});
  }
 
 }
 
 public void mutex(String path, ZkVoidCallBack zkLockCallback, long time, TimeUnit timeUnit) throws ZkLockException {
  String finalPath = this.getLockPath(path);
  InterProcessMutex mutex = new InterProcessMutex(this.client, finalPath);
 
  try {
   if (!mutex.acquire(time, timeUnit)) {
    throw new ZkLockException("acquire zk lock return false");
   }
  } catch (Exception var13) {
   throw new ZkLockException("acquire zk lock failed.", var13);
  }
 
  try {
   zkLockCallback.response();
  } finally {
   this.releaseLock(finalPath, mutex);
  }
 
 }
 
 public String getLockPath(String customPath) {
  if (!StringUtils.startsWith(customPath, "/")) {
   customPath = Constant.keyBuilder(new Object[]{"/", customPath});
  }
 
  String finalPath = Constant.keyBuilder(new Object[]{this.lockRootPath, "", customPath});
  return finalPath;
 }
 
 private void deleteInternal(String finalPath) {
  try {
   ((ErrorListenerPathable)this.client.delete().inBackground()).forPath(finalPath);
  } catch (Exception var3) {
   this.logger.info("delete zk node path:{} failed", finalPath);
  }
 
 }
 
 public void del(String customPath) {
  String lockPath = "";
 
  try {
   lockPath = this.getLockPath(customPath);
   ((ErrorListenerPathable)this.client.delete().inBackground()).forPath(lockPath);
  } catch (Exception var4) {
   this.logger.info("delete zk node path:{} failed", lockPath);
  }
 
 }
}
@FunctionalInterface
public interface ZkLockCallback<T> {
T doInLock();
}
@FunctionalInterface
public interface ZkVoidCallBack {
void response();
}
public class ZkLockException extends Exception {
public ZkLockException() {
}
public ZkLockException(String message) {
super(message);
}
public ZkLockException(String message, Throwable cause) {
super(message, cause);
}
}

配置CuratorConfig


@Configuration
public class CuratorConfig {
@Value("${zk.connectionString}")
private String connectionString;
@Value("${zk.sessionTimeoutMs:500}")
private int sessionTimeoutMs;
@Value("${zk.connectionTimeoutMs:500}")
private int connectionTimeoutMs;
@Value("${zk.dLockRoot:/dLock}")
private String dLockRoot;
@Bean
public CuratorFactoryBean curatorFactoryBean() {
return new CuratorFactoryBean(connectionString, sessionTimeoutMs, connectionTimeoutMs);
}
@Bean
@Autowired
public DLock dLock(CuratorFramework client) {
return new DLock(dLockRoot, client);
}
}

测试代码

@RestController
@RequestMapping("/dLock")
public class LockController {
@Autowired
private DLock dLock;
@RequestMapping("/lock")
public Map testDLock(String no){
final String path = Constant.keyBuilder("/test/no/", no);
Long mutex=0l;
try {
System.out.println("在拿锁:"+path+System.currentTimeMillis());
mutex = dLock.mutex(path, () -> {
try {
System.out.println("拿到锁了" + System.currentTimeMillis());
Thread.sleep(10000);
System.out.println("操作完成了" + System.currentTimeMillis());
} finally {
return System.currentTimeMillis();
}
}, 1000, TimeUnit.MILLISECONDS);
} catch (ZkLockException e) {
System.out.println("拿不到锁呀"+System.currentTimeMillis());
}
return Collections.singletonMap("ret",mutex);
}
@RequestMapping("/dlock")
public Map testDLock1(String no){
final String path = Constant.keyBuilder("/test/no/", no);
Long mutex=0l;
try {
System.out.println("在拿锁:"+path+System.currentTimeMillis());
InterProcessMutex processMutex = dLock.mutex(path);
processMutex.acquire();
System.out.println("拿到锁了" + System.currentTimeMillis());
Thread.sleep(10000);
processMutex.release();
System.out.println("操作完成了" + System.currentTimeMillis());
} catch (ZkLockException e) {
System.out.println("拿不到锁呀"+System.currentTimeMillis());
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return Collections.singletonMap("ret",mutex);
}
@RequestMapping("/del")
public Map delDLock(String no){
final String path = Constant.keyBuilder("/test/no/", no);
dLock.del(path);
return Collections.singletonMap("ret",1);
}
}

以上所述是小编给大家介绍的Java(SpringBoot)基于zookeeper的分布式锁实现详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Apache Curator库来实现Java中使用Zookeeper实现分布式锁。Curator提供了一个InterProcessMutex类来实现分布式锁。 下面是一个简单的示例代码: ```java import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.retry.ExponentialBackoffRetry; // 创建 CuratorFramework 实例 CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(1000, 3)); client.start(); // 创建分布式锁 InterProcessMutex lock = new InterProcessMutex(client, "/locks/my_lock"); // 获取锁 lock.acquire(); try { // 在此处执行临界代码 } finally { // 释放锁 lock.release(); } ``` 请注意,上面的代码是示例,在生产环境中应该使用try-with-resources语句来确保锁能正确释放。 ### 回答2: 实现Zookeeper分布式锁Java代码步骤如下: 1. 引入ZooKeeper的相关依赖:在项目的pom.xml文件中添加ZooKeeper依赖。 2. 创建一个ZooKeeper连接:使用ZooKeeper提供的API创建与ZooKeeper服务器的连接。 3. 创建锁节点:在ZooKeeper中创建一个永久节点作为锁节点。 4. 尝试获取锁:在需要获取锁的代码处,使用ZooKeeper的create()方法创建一个临时顺序节点。 5. 获取当前所有的锁节点:使用ZooKeeper的getChildren()方法获取锁节点的子节点。 6. 判断当前节点是否为最小的节点:比较当前节点和获取到的所有节点中最小的节点,如果当前节点是最小的节点,则表示获取到了分布式锁。 7. 如果当前节点不是最小的节点,则监听前一个节点的删除事件。 8. 如果前一个节点被删除,则再次检查当前节点是否是最小节点。如果是,则获取到了分布式锁。 9. 当前节点没有获取到锁时,使用ZooKeeper的exists()方法对前一个节点进行监听。 10. 当获取到锁后执行相应的业务逻辑。 11. 业务逻辑执行完毕后,通过删除当前节点释放锁。 12. 关闭ZooKeeper连接。 以上是一个基本实现分布式锁的框架,可以根据具体业务需求进行相应的优化和改进。 ### 回答3: 实现Zookeeper分布式锁需要以下步骤: 1. 创建Zookeeper连接:使用ZooKeeper类初始化Zookeeper连接,指定Zookeeper服务器的地址和超时时间。 2. 创建锁节点:使用create方法在Zookeeper上创建一个持久顺序节点来作为锁节点。这里需要考虑到可能的并发性,可以使用ThreadID等加前缀构建有序节点的名称。 3. 获取锁:使用getChildren方法获取当前所有的锁节点,然后判断自己创建的锁节点是否是最小节点。如果是最小节点,表示成功获取锁,执行相应逻辑;否则,监听前一个节点的删除事件。 4. 监听前一个节点的删除事件:在获取锁失败的情况下,使用exist方法对前一个节点进行监听。当前一个节点被删除后,重新尝试获取锁。 5. 释放锁:执行完逻辑后,使用delete方法删除自己创建的锁节点,释放资源。 示例代码如下: ```java import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; public class ZookeeperLock { private ZooKeeper zooKeeper; private CountDownLatch countDownLatch; private static final String ZOOKEEPER_ADDRESS = "localhost:2181"; private static final int SESSION_TIMEOUT = 5000; private static final String LOCK_NODE = "/lock"; public ZookeeperLock() { try { zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { countDownLatch.countDown(); } } }); countDownLatch.await(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } createLockNode(); } private void createLockNode() { try { zooKeeper.create(LOCK_NODE, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } } public void lock() { String lockNode = null; try { lockNode = zooKeeper.create(LOCK_NODE + "/", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); List<String> list = zooKeeper.getChildren(LOCK_NODE, false); String minNode = getMinNode(list); if (lockNode.equals(LOCK_NODE + "/" + minNode)) { // get the lock System.out.println("Lock acquired"); } else { Stat stat = zooKeeper.exists(LOCK_NODE + "/" + minNode, true); if (stat != null) { synchronized (stat) { stat.wait(); } } } } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } } public void unlock() { try { zooKeeper.delete(LOCK_NODE + "/", -1); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } } private String getMinNode(List<String> list) { String minNode = list.get(0); for (String node : list) { if (node.compareTo(minNode) < 0) { minNode = node; } } return minNode; } } ``` 以上是一个简单的使用Java代码实现Zookeeper分布式锁的例子。在lock方法中,当获取到锁后,会打印"Lock acquired",当释放锁后,可以继续执行后续逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值