基于org.I0Itec.zkclient.ZkClient实现分布式锁

文章目录

  • 使用ZkClient来连接zookeeper
  • 使用EPHEMERAL_SEQUENTIAL节点来加锁

使用ZkClient来连接zookeeper

	<bean id="zkCient" class="org.I0Itec.zkclient.ZkClient">
		<constructor-arg type="java.lang.String"
			value="${zookeeper.addr}" />
		<constructor-arg type="int" value="3000" />
	bean>

 

使用EPHEMERAL_SEQUENTIAL节点来加锁

import java.util.Collections;
import java.util.List;

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

public class DistributedLock {
	private static final Logger LOGGER = LoggerFactory.getLogger(DistributedLock.class);

	private final ZkClient zk;
	private final String lockName;
	private final String zkPath;
	private final long threadId;
	private String lockPath;

	/**
	 * 分布式锁
	 * 
	 * @param zk           org.I0Itec.zkclient.ZkClient
	 * @param lockBasePath 锁节点所在的目录,推荐使用:/<公司全称>/<系统简称>/DistributedLock
	 * @param lockName     锁节点的名称,不要使用特殊字符,要包含业务含义
	 */
	public DistributedLock(ZkClient zk, String lockBasePath, String lockName) {
		this.zk = zk;
		this.lockName = lockName;
		this.zkPath = lockBasePath + (lockBasePath.endsWith("/") ? "" : "/") + this.lockName;
		this.threadId = Thread.currentThread().getId();
	}

	/**
	 * 分布式锁
	 * 
	 * @param zk       org.I0Itec.zkclient.ZkClient
	 * @param lockName 锁节点的名称,不要使用特殊字符,要包含业务含义
	 */
	public DistributedLock(ZkClient zk, String lockName) {
		this(zk, "/com/xxx/yyy/DistributedLock", lockName);
	}

	/*
	 * 监听子节点的变动
	 */
	private class ZkChildListener implements IZkChildListener {
		final Object lock;

		public ZkChildListener(Object lockObj) {
			this.lock = lockObj;
		}

		@Override
		public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
			synchronized (this.lock) {
				long threadId = Thread.currentThread().getId();
				String firstNodeName = getFirstNodeName(currentChilds, lockName);
				if (firstNodeName.length() > 0 && lockPath.endsWith(firstNodeName)) {
					LOGGER.debug(String.format("线程%s,%s", threadId, "监听到子节点变化,成功获取锁"));
					this.lock.notifyAll();
				} else {
					LOGGER.debug(String.format("线程%s,%s", threadId, "监听到子节点变化,继续等待锁"));
				}
			}
		}
	}

	private static String getFirstNodeName(List<String> nodeNames, String lockName) {
		// 节点名称格式为lockName000000000X,可按字符串简单排序
		Collections.sort(nodeNames);
		for (String nodeName : nodeNames) {
			if (nodeName.startsWith(lockName)) {
				return nodeName;
			}
		}
		return "";
	}

	private String getSequence() {
		String result = null;
		for (int i = 0; i < 1000; i++) {
			try {
				zk.createPersistent(this.zkPath, true);
				// 其他线程在此时退出锁并删除了空目录zkPath,则会导致以下语句抛出ZkNoNodeException
				result = zk.createEphemeralSequential(this.zkPath + "/" + this.lockName, null);
			} catch (org.I0Itec.zkclient.exception.ZkNoNodeException ex) {
				continue;
			}
			break;
		}
		return result;
	}

	/**
	 * 尝试获取锁,获取失败的话,不需要再执行releaseLock
	 * 
	 * @return true:获得锁成功, false:获得锁失败
	 */
	public boolean getLock() {
		lockPath = getSequence();
		if (lockPath == null) {
			return false;
		}
		List<String> nodes = zk.getChildren(this.zkPath);
		String firstNodeName = getFirstNodeName(nodes, this.lockName);
		nodes = null;
		if (lockPath.endsWith(firstNodeName)) {
			// 成功获取锁
			return true;
		}
		// 否则立即删除当前创建的锁节点
		releaseLock();
		return false;
	}

	/*
	 * 等待,直到锁成功获取
	 */
	public void waitUntilLock() throws InterruptedException {
		lockPath = getSequence();
		if (lockPath == null) {
			throw new InterruptedException("fail to create lock path");
		}

		LOGGER.debug(String.format("线程%s,%s", threadId, "初始化子节点"));
		final Object lock = new Object();
		synchronized (lock) {
			// 独占lock对象后,先监听子节点变化
			IZkChildListener listener = new ZkChildListener(lock);
			// 在当前执行线程释放lock对象后,监听线程才会开始处理节点变化
			zk.subscribeChildChanges(this.zkPath, listener);
			try {
				// 获取子节点
				List<String> nodes = zk.getChildren(this.zkPath);
				String firstNodeName = getFirstNodeName(nodes, this.lockName);
				nodes = null;
				if (lockPath.endsWith(firstNodeName)) {
					return;
				}
				LOGGER.debug(String.format("线程%s,%s", threadId, "等待锁"));
				// 释放对lock对象的独占,并等待监听线程在lock对象上发出通知
				lock.wait();
			} finally {
				if (listener != null) {
					zk.unsubscribeChildChanges(this.zkPath, listener);
					listener = null;
				}
				LOGGER.debug(String.format("线程%s,%s", threadId, "成功获取锁后,释放监听"));
			}
		}
	}

	/*
	 * 主动释放锁
	 */
	public void releaseLock() {
		if (lockPath != null) {
			zk.delete(lockPath, -1);
			try {
				zk.delete(zkPath, -1);
			} catch (Exception ex) {
				// 有其他线程获取锁时,删除非空目录会失败,属于正常情况
			}
			LOGGER.debug(String.format("线程%s,%s", threadId, "释放锁"));
			lockPath = null;
		}
	}
}

你可能感兴趣的:(java)