首页 > 其他分享 >ZooKeeper : Curator框架之分布式锁InterProcessSemaphoreMutex

ZooKeeper : Curator框架之分布式锁InterProcessSemaphoreMutex

时间:2022-11-09 19:05:49浏览次数:56  
标签:InterProcessSemaphoreMutex thread ZooKeeper Curator curator org public pool 分布式


InterProcessSemaphoreMutex

​InterProcessSemaphoreMutex​​类的源码注释:

A NON re-entrant mutex that works across JVMs. Uses Zookeeper to hold the lock. All processes in all JVMs that use the same lock path will achieve an inter-process critical section.

跨​​JVM​​​工作的不可重入互斥锁。使用​​Zookeeper​​​来持有锁。所有​​JVM​​中使用相同锁路径的所有进程都将实现进程间临界区。

与​​InterProcessMutex​​​类似,也是公平的,每个用户都将按照请求的顺序获得互斥锁(从​​ZK​​的角度来看),但此锁不可重入。

  • ​​ZooKeeper : Curator框架之分布式锁InterProcessMutex​​

​InterProcessSemaphoreMutex​​类的可用方法比较少:

ZooKeeper : Curator框架之分布式锁InterProcessSemaphoreMutex_分布式

测试

​pom.xml​​:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.kaven</groupId>
<artifactId>zookeeper</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
</dependencies>
</project>

​CuratorFrameworkProperties​​​类(提供​​CuratorFramework​​需要的一些配置信息):

package com.kaven.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorFrameworkProperties {
// 连接地址
public static final String CONNECT_ADDRESS = "192.168.1.3:9000";
// 连接超时时间
public static final int CONNECTION_TIMEOUT_MS = 40000;
// Session超时时间
public static final int SESSION_TIMEOUT_MS = 10000;
// 命名空间
public static final String NAMESPACE = "MyNamespace";
// 重试策略
public static final RetryPolicy RETRY_POLICY = new ExponentialBackoffRetry(1000, 3);
}

​InterProcessSemaphoreMutexRunnable​​​类(实现了​​Runnable​​接口,模拟分布式节点获取分布式锁):

package com.kaven.zookeeper;

import lombok.SneakyThrows;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;

import java.util.Random;

public class InterProcessSemaphoreMutexRunnable implements Runnable{
@SneakyThrows
@Override
public void run() {
// 使用不同的CuratorFramework实例,表示不同的分布式节点
CuratorFramework curator = getCuratorFramework();
curator.start();
assert curator.getState().equals(CuratorFrameworkState.STARTED);

// 模拟随机加入的分布式节点
int randomSleep = new Random().nextInt(1000);
Thread.sleep(randomSleep);

// 分布式锁的锁路径
String path = "/kaven";

// 创建InterProcessSemaphoreMutex实例,用于获取分布式锁
InterProcessSemaphoreMutex mutex =
new InterProcessSemaphoreMutex(curator, path);

// 阻塞,直到获取分布式锁
mutex.acquire();
if(mutex.isAcquiredInThisProcess()) {
System.out.println(Thread.currentThread().getName() + " 持有分布式锁");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " 释放分布式锁");
mutex.release();
}
else {
throw new RuntimeException("获取分布式锁时被中断");
}
}

private CuratorFramework getCuratorFramework() {

// 创建CuratorFramework实例
return CuratorFrameworkFactory.builder()
.connectString(CuratorFrameworkProperties.CONNECT_ADDRESS)
.retryPolicy(CuratorFrameworkProperties.RETRY_POLICY)
.connectionTimeoutMs(CuratorFrameworkProperties.CONNECTION_TIMEOUT_MS)
.sessionTimeoutMs(CuratorFrameworkProperties.SESSION_TIMEOUT_MS)
.namespace(CuratorFrameworkProperties.NAMESPACE)
.build();
}
}

启动类:

package com.kaven.zookeeper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Application {
private static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool();

public static void main(String[] args) throws Exception {
for (int i = 0; i < 5; i++) {
EXECUTOR_SERVICE.execute(new InterProcessSemaphoreMutexRunnable());
}
Thread.sleep(10000000);
}
}

模拟​​5​​个分布式节点获取分布式锁,输出如下所示:

pool-1-thread-4 持有分布式锁
pool-1-thread-4 释放分布式锁
pool-1-thread-5 持有分布式锁
pool-1-thread-5 释放分布式锁
pool-1-thread-3 持有分布式锁
pool-1-thread-3 释放分布式锁
pool-1-thread-1 持有分布式锁
pool-1-thread-1 释放分布式锁
pool-1-thread-2 持有分布式锁
pool-1-thread-2 释放分布式锁

​InterProcessSemaphoreMutex​​​提供了带有超时机制的获取锁的方法(​​acquire(long time, TimeUnit unit)​​)。

// 阻塞,直到获取分布式锁或给定时间已到
mutex.acquire(10, TimeUnit.SECONDS);
if(mutex.isAcquiredInThisProcess()) {
System.out.println(Thread.currentThread().getName() + " 持有分布式锁");
Thread.sleep(20000);
System.out.println(Thread.currentThread().getName() + " 释放分布式锁");
mutex.release();
}
else {
System.out.println(Thread.currentThread().getName() + " 获取分布式锁超时");
}

输出如下所示:

pool-1-thread-4 持有分布式锁
pool-1-thread-1 获取分布式锁超时
pool-1-thread-5 获取分布式锁超时
pool-1-thread-3 获取分布式锁超时
pool-1-thread-2 获取分布式锁超时
pool-1-thread-4 释放分布式锁

​Curator​​​框架的分布式锁​​InterProcessSemaphoreMutex​​就介绍到这里,如果博主有说错的地方或者大家有不同的见解,欢迎大家评论补充。


标签:InterProcessSemaphoreMutex,thread,ZooKeeper,Curator,curator,org,public,pool,分布式
From: https://blog.51cto.com/u_15870611/5838286

相关文章

  • Canal:ZooKeeper进行集群管理
    集成ZooKeeper前期回顾:​​Canal:部署Canal与CanalAdmin​​搭建​​ZooKeeper​​可以参考下面这几篇博客:​​ZooKeeper:Shell脚本搭建单机版ZooKeeper​​​​ZooKeeper:......
  • 1 zookeeper介绍
     https://mirror.bit.edu.cn/apache/zookeeper/https://www.cnblogs.com/sakura-yxf/p/12020348.html 1Zookeeper集群的角色:Leader和follower(Observer) 只要集群......
  • 2 zookeeper安装
    zookeeper包下载:https://mirror.bit.edu.cn/apache/zookeeper/1下载解压,修改配置zookeeper下载:http://archive.apache.org/dist/zookeeper/https://www.aboutyun.co......
  • zookeeper启动闪退问题
    在配置zookeeper集群时,遇到启动zookeeper后几秒就闪退经过一系列疯狂查找后解决问题方法一:在zookeeper的配置文件zoo.cfg中在/zkData/installed里面查找zookeeper_serv......
  • ZooKeeper系列:实现分布式锁
    锁是为了在多线程的场景中保证数据安全而增加的一种手段,Java中常用的有CountdownLatch,ReentrantLock等单应用中的锁,在现在处处都是分布式的场景需求下就不能满足了,所以就出......
  • 10-注册中心&Zookeeper设计实践课_ev 没用
                                               ......
  • 1.Zookeeper搭建使用
    安装环境准备Zookeeper需要jre环境。单机模式部署解压安装包,修改配置解压Zookeeper安装包,进入conf文件夹,复制zoo-sample.cfg为zoo.cfg,zoo.cfg是Zookeeper的配置文件。......
  • 2.Zookeeper 权限控制 ACL
    Zookeeper权限控制ACL(AccessControlList,访问控制表)ACL权限可以针对节点设置相关读写等权限,保障数据安全性。permissions可以指定不同的权限范围及角色。ACL命令......
  • zookeeper
    Zookeeper1)初识Zookeeper1.1)Zookeeper概念•Zookeeper是ApacheHadoop项目下的一个子项目,是一个树形目录服务。•Zookeeper翻译过来就是动物园管理员,他是用来......
  • ZooKeeper 安装
    1.1下载安装1、环境准备ZooKeeper服务器是用Java创建的,它运行在JVM之上。需要安装JDK7或更高版本。2、上传将下载的ZooKeeper放到/opt/ZooKeeper目录下​#上传zooke......