Skip to main content
 首页 » 编程设计

zk分布式锁-排它锁简单实现

2022年07月18日46虾米哥

package Lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DistributeLock implements Lock{
private static Logger LOG = LoggerFactory.getLogger(DistributeLock.class);
private static String ZK_IP_PORT= "192.168.0.137:2181";
private static String LOCK_NODE = "/lock";

private ZkClient client = new ZkClient(ZK_IP_PORT);
private CountDownLatch cdl = null;

@Override
public void lock() {
if(tryLock()){
return ;
}
waitForLock();
lock();
}

private void waitForLock(){
IZkDataListener listener = new IZkDataListener() {

@Override
public void handleDataDeleted(String dataPath) throws Exception {
// TODO Auto-generated method stub

}

@Override
public void handleDataChange(String dataPath, Object data) throws Exception {
if(cdl != null){
cdl.countDown();
}
}
};

client.subscribeDataChanges(LOCK_NODE, listener);
if(client.exists(LOCK_NODE)){
if(cdl != null){
cdl = new CountDownLatch(1);
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
client.unsubscribeDataChanges(LOCK_NODE, listener);
}

@Override
public void lockInterruptibly() throws InterruptedException {

}

@Override
public boolean tryLock() {
try {
client.createEphemeral(LOCK_NODE);
LOG.info("获取到锁");
return true;
} catch (Exception e) {
}
LOG.error("获取失败");
return false;
}

@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}

@Override
public void unlock() {
client.delete(LOCK_NODE);
}

@Override
public Condition newCondition() {
return null;
}

}

测试类:

package Lock;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LockTest {
private static Logger LOG = LoggerFactory.getLogger(LockTest.class);
private static int count = 10;
private static CountDownLatch cdl = new CountDownLatch(count);
public static void main(String[] args) {
for(int i = 0; i < count;i++){
new Thread(new Order()).start();
LOG.error("开启");
cdl.countDown();
}
}

static class Order implements Runnable{
private DistributeLock lock = new DistributeLock();
@Override
public void run() {
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
String orderId = GenorderId.genOrderId();

System.out.println(orderId);
lock.unlock();
}

}

static class GenorderId{
private static int index = 0;
public static String genOrderId(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddhhmmss|SSS");
return sdf.format(new Date()) + ++index;
}
}

}


本文参考链接:https://www.cnblogs.com/maohuidong/p/8433408.html