Zookeeper项目中用到的分布式锁

例子
private static boolean wasAcquired = false;// 是否获取了锁
public void tetsZookeeper(){
String serverId = UUID.randomUUID().toString().toLowerCase();
AccountLock lock = new AccountLock("/ACCOUNT/" + serverId,zookeeperConnector);
log.info(“开始获取锁”);
wasAcquired = lock.acquire(3);// 锁
log.info(“获取锁:”+(wasAcquired?“SUCCESS”:“ERROR”));
try{
System.out.println(“11111111”);
Thread.sleep(2000);
return;
}catch (Exception e){
log.error(e.getMessage(),e);
}finally {
log.info(“开始释放锁…”);
lock.release();// 释放锁
}
}

AccountLock类
package com.baibei.pay.utils;

import com.baibei.pay.configurer.ZooKeeperConnector;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;

@Slf4j
public class AccountLock {
InterProcessMutex lock;
boolean wasAcquired = false;// 是否获取到了锁

public AccountLock(String path, ZooKeeperConnector zookeeperConnector) {
lock = new InterProcessMutex(zookeeperConnector.getClient(), path);
}

/**
* 尝试加锁并等待
*
* @param timeOut
* 超时时间(秒), -1 不限时
* @return true为获取锁成功,false为获取锁失败
*
* @throws Exception
*/
public boolean acquire(int timeOut) {
try {
wasAcquired = lock.acquire(timeOut, TimeUnit.SECONDS);
} catch (Exception e) {
log.error(“get Lock time out ERROR:” + e.getMessage());
wasAcquired = false;
}
return wasAcquired;
}

/**
* 释放锁
*
* @throws Exception
*/
public void release() {
if (wasAcquired) {
try {
lock.release();
} catch (Exception e) {
log.error(“remove Lock ERROR:” + e.getMessage());
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值