springboot2整合zookeeper集成curator
步骤:
1- pom.xml
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.12.0</version>
</dependency>
2- yml配置:
zk:
url: 127.0.0.1:2181
localPath: /newlock
timeout: 3000
3- 配置类
package com.test.domi.config; import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class ZookeeperConf { @Value("${zk.url}")
private String zkUrl; @Bean
public CuratorFramework getCuratorFramework(){
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
CuratorFramework client = CuratorFrameworkFactory.newClient(zkUrl,retryPolicy);
client.start();
return client;
}
}
4- 使用
package com.test.domi.common.utils.lock; import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock; @Component("zklock")
public class ZKlock implements Lock { @Autowired
private CuratorFramework zkClient;
@Value("${zk.localPath}")
private String lockPath;
private String currentPath;
private String beforePath; @Override
public boolean tryLock() {
try {
//根节点的初始化放在构造函数里面不生效
if (zkClient.checkExists().forPath(lockPath) == null) {
System.out.println("初始化根节点==========>" + lockPath);
zkClient.create().creatingParentsIfNeeded().forPath(lockPath);
}
System.out.println("当前线程" + Thread.currentThread().getName() + "初始化根节点" + lockPath);
} catch (Exception e) {
} if (currentPath == null) {
try {
currentPath = this.zkClient.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
.forPath(lockPath + "/");
} catch (Exception e) {
return false;
}
}
try {
//此处该如何获取所有的临时节点呢?如locks00004.而不是获取/locks/order中的order作为子节点??
List<String> childrens = this.zkClient.getChildren().forPath(lockPath);
Collections.sort(childrens);
if (currentPath.equals(lockPath + "/" + childrens.get(0))) {
System.out.println("当前线程获得锁" + currentPath);
return true;
}else{
//取前一个节点
int curIndex = childrens.indexOf(currentPath.substring(lockPath.length() + 1));
//如果是-1表示children里面没有该节点
beforePath = lockPath + "/" + childrens.get(curIndex - 1);
}
} catch (Exception e) {
return false;
}
return false;
} @Override
public void lock() {
if (!tryLock()) {
waiForLock();
lock();
}
} @Override
public void unlock() {
try {
zkClient.delete().guaranteed().deletingChildrenIfNeeded().forPath(currentPath);
} catch (Exception e) {
//guaranteed()保障机制,若未删除成功,只要会话有效会在后台一直尝试删除
}
} private void waiForLock(){
CountDownLatch cdl = new CountDownLatch(1);
//创建监听器watch
NodeCache nodeCache = new NodeCache(zkClient,beforePath);
try {
nodeCache.start(true);
nodeCache.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
cdl.countDown();
System.out.println(beforePath + "节点监听事件触发,重新获得节点内容为:" + new String(nodeCache.getCurrentData().getData()));
}
});
} catch (Exception e) {
}
//如果前一个节点还存在,则阻塞自己
try {
if (zkClient.checkExists().forPath(beforePath) == null) {
cdl.await();
}
} catch (Exception e) {
}finally {
//阻塞结束,说明自己是最小的节点,则取消watch,开始获取锁
try {
nodeCache.close();
} catch (IOException e) {
}
}
} @Override
public void lockInterruptibly() throws InterruptedException {
} @Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
} @Override
public Condition newCondition() {
return null;
} }
5- 调用demo
package com.test.domi.controller; import com.test.domi.common.utils.ZkUtil;
import com.test.domi.common.utils.lock.ZKlock;
import org.I0Itec.zkclient.ZkClient;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/zk")
public class ZKController { @Autowired
private CuratorFramework zkClient;
// @Autowired
// private ZkClient zkClient; private String url = "127.0.0.1:2181";
private int timeout = 3000;
private String lockPath = "/testl";
@Autowired
private ZKlock zklock;
private int k = 1; @GetMapping("/lock")
public Boolean getLock() throws Exception{ for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
zklock.lock(); zklock.unlock();
} }).start(); }
return true; } }
springboot2整合zookeeper集成curator的更多相关文章
- SpringBoot2 整合 Zookeeper组件,管理架构中服务协调
本文源码:GitHub·点这里 || GitEE·点这里 一.Zookeeper基础简介 1.概念简介 Zookeeper是一个Apache开源的分布式的应用,为系统架构提供协调服务.从设计模式角度来 ...
- SpringBoot2整合activiti6环境搭建
SpringBoot2整合activiti6环境搭建 依赖 <dependencies> <dependency> <groupId>org.springframe ...
- SpringBoot2 整合Kafka组件,应用案例和流程详解
本文源码:GitHub·点这里 || GitEE·点这里 一.搭建Kafka环境 1.下载解压 -- 下载 wget http://mirror.bit.edu.cn/apache/kafka/2.2 ...
- SpringBoot2 整合Ehcache组件,轻量级缓存管理
本文源码:GitHub·点这里 || GitEE·点这里 一.Ehcache缓存简介 1.基础简介 EhCache是一个纯Java的进程内缓存框架,具有快速.上手简单等特点,是Hibernate中默认 ...
- (十七)整合 Zookeeper组件,管理架构中服务协调
整合 Zookeeper组件,管理架构中服务协调 1.Zookeeper基础简介 1.1 基本理论 1.2 应用场景 2.安全管理操作 2.1 操作权限 2.2 认证方式: 2.3 Digest授权流 ...
- Zookeeper客户端Curator使用详解
Zookeeper客户端Curator使用详解 前提 最近刚好用到了zookeeper,做了一个基于SpringBoot.Curator.Bootstrap写了一个可视化的Web应用: zookeep ...
- zookeeper(六):Zookeeper客户端Curator的API使用详解
简介 Curator是Netflix公司开源的一套zookeeper客户端框架,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连.反复注册Watcher和NodeExistsEx ...
- java springboot整合zookeeper入门教程(增删改查)
java springboot整合zookeeper增删改查入门教程 zookeeper的安装与集群搭建参考:https://www.cnblogs.com/zwcry/p/10272506.html ...
- 转:Zookeeper客户端Curator使用详解
原文:https://www.jianshu.com/p/70151fc0ef5d Zookeeper客户端Curator使用详解 前提 最近刚好用到了zookeeper,做了一个基于SpringBo ...
随机推荐
- BZOJ2208连通数
还是挺简单的tarjan. 判断时可能重复,直接bitset搞定. 首先tarjan缩点,每个scc的内部肯定能互相到达,更一下,而且一个scc里的各个点的贡献肯定是一样的,topsort,更新答案就 ...
- 12.数值的整数次方 Java
题目描述 给定一个double类型的浮点数base和int类型的整数exponent.求base的exponent次方. 这道题看似简单,其实BUG重重.要注意的问题: 1 关于次幂的问题特殊的情况, ...
- 新版uni-app 在微信小工具调试遇到报错解决方案
问题描述:我在运行到微信小程序是运行报错打不开微信小程序报错如下图 结局方案:将微信小程序安全设置开启如下图
- java连接mysql出现The server time zone value '�й���ʱ��' is unrecognized or represents more than...
在连接的配置文件中,指定数据库位置的末尾加上serverTimezone=UTC ```yml url: jdbc:mysql://localhost:3306/app?serverTimezone= ...
- python文件夹中pycache文件是什么
python(pycache文件的问题):python属于脚本语言,执行python文件需要通过python解释器将源码转换为字节码,然后供cpu读取,pycache文件夹里面保存的就是py文件对应的 ...
- LeetCode 48. 旋转图像(Rotate Image)
题目描述 给定一个 n × n 的二维矩阵表示一个图像. 将图像顺时针旋转 90 度. 说明: 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵.请不要使用另一个矩阵来旋转图像. 示例 1: ...
- XAMPP是什么?
XAMPP=Apache + MySQL + PHP + Perl,是一个完全免费,易于安装和使用Apache发行版,包含了Apache.MySQL.PHP和Perl.支持Windows.Linux和 ...
- Jmeter如何使用数据库返回值实践
Jmeter如何使用数据库返回值实践 最近使用Jmeter针对产品做性能测试,测试内容是要模拟300并发用户审批休假申请时的性能.由于每个申请人的主管不同,且会根据不同的休假类型,会有一级审批或者二级 ...
- Spark3.0 preview预览版尝试GPU调用(本地模式不支持GPU)
Spark3.0 preview预览版可以下载使用,地址:https://archive.apache.org/dist/spark/spark-3.0.0-preview/,pom.xml也可以进行 ...
- Linux 服务器基本优化
一:修改ulimit数 vi /etc/security/limits.conf 添加如下行: * soft noproc 65535 * hard noproc 65535 * soft nofil ...