借助Zookeeper实现排他锁

        排他锁:又称写锁或者独占锁,是一种基本的锁类型。如果事务T1对数据O加上排他锁之后,那么在整个加锁期间,只允许事务T1对数据O进行读写和更新操作,其他任何事务都不能再对这个数据进行任何的类型的操作,直到T1释放了排他锁。

        获取锁原理:在Zookeeper中,多个客户端通过create() 接口创建同一个节点,zookeeper会保证最终只有一个客户端能够创建成功;那么可以认为创建节点成功的客户端获取到了锁,没有创建节点成功的客户端没有获取到锁,没有获取到锁的客户端然后注册一个节点变更的Watcher监听,当这个节点删除后再去创建,直到创建成功(获取到锁)。

        释放锁原理:1、因为客户端创建的节点是一个临时节点,所以当获取到锁的客户端发生了岩机,zookeeper上的这个临时节点会被移除;2、获取到锁的客户端,正常执行完业务逻辑后,客户端会主动将自己创建的临时节点删除。

        简单的代码实现:代码中只实现了正常的获取锁和释放锁的逻辑。

// 定义一个锁接口
public interface Lock {

	boolean lock();
	void unLock();
}

/**
 * 分布式排他锁
 * 		支持重入
 *
 */
public class MutexLock implements Lock {

	private static final String MUTEX_LOCK_ROOT = "/mutex-lock-root";
	
	private final String lockName;
	
	private final ConcurrentMap<Thread, LockData> threadData = Maps.newConcurrentMap();

	@SuppressWarnings("unused")
    private static class LockData {
		final Thread owningThread;
        final AtomicInteger lockCount = new AtomicInteger(1);

        private LockData(Thread owningThread)
        {
            this.owningThread = owningThread;
        }
    }
	
	public MutexLock(String lockName) {
		this.lockName = PathUtils.validatePath(MUTEX_LOCK_ROOT + "-" + lockName);
	}
	
	@Override
	public boolean lock() {
		boolean result = true;
		Thread currentThread = Thread.currentThread();
		LockData lockData = threadData.get(currentThread);
		if (null != lockData) {
			lockData.lockCount.incrementAndGet();
			return result;
		}
		
		try {
			String lockPath = innerLock();
			if (StringUtils.isNotEmpty(lockPath)) {
				lockData = new LockData(currentThread);
				threadData.put(currentThread, lockData);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
		}
		return result;
	}

	@Override
	public void unLock() {
		Thread currentThread = Thread.currentThread();
		LockData lockData = threadData.get(currentThread);
		if (null == lockData) {
			return;
		}
		int count = lockData.lockCount.decrementAndGet();
		if (0 < count) {
			return;
		}
		threadData.remove(currentThread);
		// 允许重试5次
		ZooKeeper zooKeeper = LockUtils.newZookeeper();
		int retry = 5;
		while (retry-- > 0) {
			try {
				zooKeeper.delete(lockName, -1);
				retry = 0;
			} catch (InterruptedException | KeeperException e) {
				e.printStackTrace();
			}
		}
	}
	
	private String innerLock() throws Exception {
		final ZooKeeper zooKeeper = LockUtils.newZookeeper();
		CountDownLatch countDownLatch = new CountDownLatch(1);
		String result = createPath(zooKeeper, countDownLatch);
		countDownLatch.await();
		while (StringUtils.isEmpty(result)) {
			result = createPath(zooKeeper, countDownLatch);
		}
		return result;
	}

	private String createPath(ZooKeeper zooKeeper, CountDownLatch countDownLatch) {
		String resultPath = null;
		try {
			// 创建临时节点
			resultPath = zooKeeper.create(lockName, "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
			// 创建成功
			countDownLatch.countDown();
		} catch (KeeperException.NodeExistsException e) {
			// 节点存在
			watchPath(zooKeeper, countDownLatch);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultPath;
	}
	
	private void watchPath(ZooKeeper zooKeeper, CountDownLatch countDownLatch) {
		try {
			Stat stat = zooKeeper.exists(lockName, new Watcher() {
				@Override
				public void process(WatchedEvent event) {
					if (EventType.NodeDeleted == event.getType()) {
						countDownLatch.countDown();
					}
				}	
			});
			if (null == stat) {
				//节点不存在
				countDownLatch.countDown();
			}
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
}

public class LockUtils {

	private static ZooKeeper zooKeeper;
	
	public static ZooKeeper newZookeeper() {
		if (null == zooKeeper) {
			init();
		}
		return zooKeeper;
	}
	
	private static void init() {
		if (null == zooKeeper) {
			synchronized (LockUtils.class) {
				if (null == zooKeeper) {
					try {
						CountDownLatch countDownLatch = new CountDownLatch(1);
						zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new Watcher() {

							@Override
							public void process(WatchedEvent event) {
								if (KeeperState.SyncConnected == event.getState()) {
									countDownLatch.countDown();
								}
							}
							
						});
						countDownLatch.await();
						System.out.println("=======init success========");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}

        测试结果:

public class TestLock {

	public static void main(String[] args) {
		LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.getLogger("org.apache.zookeeper").setLevel(Level.valueOf("info"));
        new TestLock().test();
	}
	
	private void test() {
		final Lock lock = new MutexLock("test");
		CountDownLatch countDownLatch = new CountDownLatch(1);
		for (int i=0; i<10; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					try {
						countDownLatch.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (lock.lock()) {
						System.out.println("one  " + Thread.currentThread().getName() + "----- 当前时间 : " + System.currentTimeMillis());
						if (lock.lock()) {
							System.out.println("two  " + Thread.currentThread().getName() + "----- 当前时间 : " + System.currentTimeMillis());
							lock.unLock();
						}
						lock.unLock();
					}
				}
			}).start();
		}
		countDownLatch.countDown();
	}
}

测试结果:
one  Thread-0----- 当前时间 : 1561083459488
two  Thread-0----- 当前时间 : 1561083459488
one  Thread-9----- 当前时间 : 1561083459821
two  Thread-9----- 当前时间 : 1561083459823
one  Thread-4----- 当前时间 : 1561083459880
two  Thread-4----- 当前时间 : 1561083459880
one  Thread-7----- 当前时间 : 1561083459925
two  Thread-7----- 当前时间 : 1561083459925
one  Thread-5----- 当前时间 : 1561083459964
two  Thread-5----- 当前时间 : 1561083459964
one  Thread-6----- 当前时间 : 1561083459996
two  Thread-6----- 当前时间 : 1561083459996
one  Thread-3----- 当前时间 : 1561083460079
two  Thread-3----- 当前时间 : 1561083460079
one  Thread-2----- 当前时间 : 1561083460409
two  Thread-2----- 当前时间 : 1561083460409
one  Thread-1----- 当前时间 : 1561083460433
two  Thread-1----- 当前时间 : 1561083460433
one  Thread-8----- 当前时间 : 1561083460447
two  Thread-8----- 当前时间 : 1561083460447

 

### ZooKeeper 分布式实现与使用 #### 1. ZooKeeper 分布式的核心概念 ZooKeeper 是一种分布式的协调服务工具,能够通过其核心特性(如顺序节点、临时节点以及监听器机制)来实现分布式的功能。分布式是一种用于控制多个进程或线程访问共享资源的方式,在分布式环境中尤为重要。 为了确保分布式系统的正常运行,ZooKeeper 提供了一种基于 ZNode 的定机制。这种机制利用了 ZooKeeper 中的 **顺序节点** 和 **临时节点** 特性[^1]。当客户端尝试获取时,它会在指定路径下创建一个带有前缀的顺序节点;随后,客户端会检查当前创建的节点是否是最小序号的节点。如果是,则认为该客户端成功获得了。 #### 2. 的获取流程 在 ZooKeeper实现分布式的过程中,的获取主要分为以下几个逻辑操作: - 客户端向特定路径 `/locks` 下创建一个带有序列编号的临时节点。 - 随后,客户端检索该路径下的所有子节点列表,并找到自己所创建的节点位置。 - 如果发现自己的节点是序列最小的一个,则表示已获得。 - 否则,客户端需要监视比自己节点序列小一位的那个节点的状态变化事件。一旦被监控的节点删除,再次重复上述过程直至成功获取为止。 #### 3. 的释放流程 当持有的任务完成之后,应该主动调用方法去移除之前建立起来的对应节点,从而触发其他等待中的客户重新竞争资源的过程。具体来说就是删除先前由本客户端创建出来的那个唯一标识符形式存在的 znode 节点实例。 #### 4. 异常处理机制 由于网络分区或者服务器宕机等原因可能会导致某些情况下发生意外状况,因此还需要考虑一些特殊情况下的行为定义。例如,如果某个拥有的应用程序突然崩溃而未能显式地解除它的占有状态怎么办?这时可以通过设置合理的 session timeout 来解决这个问题——即只要超过一定时间未收到心跳包更新就会自动清理掉与此关联的一切事物包括那些代表“加”的 ephemeral nodes[^3]。 #### 5. 示例代码 以下是使用 Java 编写的简单版本的独占型分布式实现示例: ```java import org.apache.zookeeper.*; import java.util.Collections; import java.util.List; public class DistributedLock implements Watcher { private static final String LOCK_PATH = "/lock"; private ZooKeeper zk; public DistributedLock(String connectString) throws Exception { this.zk = new ZooKeeper(connectString, 3000, this); } @Override public void process(WatchedEvent event) {} public boolean acquireLock() throws KeeperException, InterruptedException { String lockName = zk.create(LOCK_PATH + "/lock-", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); List<String> children = zk.getChildren(LOCK_PATH, false); Collections.sort(children); int index = children.indexOf(lockName.substring((LOCK_PATH+"/").length())); if (index == 0){ System.out.println(Thread.currentThread().getName()+" acquired the lock."); return true; // Acquired the lock. }else{ Stat stat = zk.exists(LOCK_PATH+"/"+children.get(index-1),true); while(stat !=null ){ Thread.sleep(100); // Wait until previous node is deleted. stat=zk.exists(LOCK_PATH+"/"+children.get(index-1),true); } return acquireLock(); // Retry after predecessor releases its lock. } } public void releaseLock(String lockPath) throws KeeperException, InterruptedException { zk.delete(lockPath,-1); System.out.println(Thread.currentThread().getName()+ " released the lock."); } } ``` 此代码片段展示了如何手动构建基本功能上的排他性互斥模型。然而实际开发当中推荐采用像 Apache Curator 这样的第三方框架来进行封装后的高效便捷操作[^2]。 #### 总结 综上所述,借助ZooKeeper 可以轻松达成跨多台机器之间同步协作的需求目标之一—也就是所谓的全局范围内的临界区保护手段即所谓‘Distributed Lock’ 。不过需要注意的是除了正确编写业务逻辑之外还必须妥善规划好各种可能发生的错误场景以便及时做出响应动作防止出现诸如死之类的严重后果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值