原理:
利用临时顺序节点来实现分布式可重入锁
锁实现——ZKLock2
package com.test.tomcat.common;
import lombok.Data;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* @program: test
* @description:利用临时顺序节点来实现分布式锁
* 获取锁:取排队号(创建自己的临时顺序节点),然后判断自己是否是最小号,如是,则获得锁;不是,则注册前一节点的watcher,阻塞等待
* 释放锁:删除自己创建的临时顺序节点
* @author: peng.gao
* @create: 2019-07-10 19:30
**/
@Data
public class ZKLock2 implements Lock {
private String lockPath;
private ZkClient client;
/**
* 当前节点
*/
private ThreadLocal<String> currentPath = new ThreadLocal<>();
/**
* 上一
*/
private ThreadLocal<String> beforePath = new ThreadLocal<>();
/**
* 重入计数
*/
private ThreadLocal<Integer> reentrantCount = new ThreadLocal<>();
public ZKLock2(String lockPath) {
this.lockPath = lockPath;
this.client = new ZkClient("localhost:2181");
client.setZkSerializer(new MyZkSerializer());
if (!this.client.exists(lockPath)) {
try {
//创建普通节点
client.createPersistent(lockPath);
} catch (ZkNodeExistsException e) {
}
}
}
@Override
public void lock() {
if (!tryLock()) {
// 阻塞等待
waitForLock();
// 再次尝试加锁
lock();
}
}
private void waitForLock() {
CountDownLatch countDownLatch = new CountDownLatch(1);
//watcher
IZkDataListener listener = new IZkDataListener() {
@Override
public void handleDataChange(String s, Object o) throws Exception {
}
@Override
public void handleDataDeleted(String s) throws Exception {
System.out.println("-----监听到节点被删除");
countDownLatch.countDown();
}
};
//给前一个节点注册监听器
client.subscribeDataChanges(this.beforePath.get(), listener);
if (this.client.exists(beforePath.get())) {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 节点删除后,取消watcher
client.unsubscribeDataChanges(this.beforePath.get(), listener);
}
@Override
public boolean tryLock() {
//可重入锁处理
if (this.reentrantCount.get() != null) {
int count = this.reentrantCount.get();
if (count > 0) {
this.reentrantCount.set(++count);
return true;
}
}
if (this.currentPath.get() == null) {
//创建临时顺序节点
currentPath.set(this.client.createEphemeralSequential(lockPath + "/", "aaa"));
}
//获取所有的子节点
List<String> children = this.client.getChildren(lockPath);
//排序
Collections.sort(children);
//判断当前节点是否是最小值
if (currentPath.get().equals(lockPath + "/" + children.get(0))) {
this.reentrantCount.set(1);
return true;
} else {
// 取到当前节点的位置索引
int curIndex = children.indexOf(currentPath.get().substring(lockPath.length() + 1));
//设置前一个节点
beforePath.set(lockPath + "/" + children.get(curIndex - 1));
}
return false;
}
@Override
public void unlock() {
//重入锁释放处理
if (this.reentrantCount.get() != null) {
int count = this.reentrantCount.get();
if (count > 1) {
this.reentrantCount.set(--count);
return;
} else {
this.reentrantCount.set(null);
}
}
//删除当前节点
this.client.delete(currentPath.get());
}
public static void main(String[] args) throws InterruptedException {
int count = 50;
//循环屏障
CyclicBarrier cb = new CyclicBarrier(count);
for (int i = 0; i < count; i++) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-------我准备好-------");
//等待一起执行
try {
cb.await();
} catch (Exception e) {
e.printStackTrace();
}
ZKLock2 lock = new ZKLock2("/zkLock22");
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + "-------获得了锁-------");
} finally {
lock.unlock();
}
}
}).start();
}
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public Condition newCondition() {
return null;
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
}
ZK序列化实现——MyZkSerializer
package com.test.tomcat.common;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import java.io.UnsupportedEncodingException;
/**
* @program: test
* @description:
* @author: peng.gao
* @create: 2019-07-10 00:05
**/
public class MyZkSerializer implements ZkSerializer {
private static final String charset = "utf-8";
@Override
public byte[] serialize(Object o) throws ZkMarshallingError {
try {
return String.valueOf(o).getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError(e);
}
}
@Override
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
try {
return new String(bytes,charset);
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError(e);
}
}
}