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 ...
随机推荐
- c++ gdb调试的基本使用
https://blog.csdn.net/zdy0_2004/article/details/80102076
- zookeeper系列(一)zookeeper图形化的客户端工具
追加一个zookeeper图形化的客户端工具: 1.zookeeper图像化客户端工具的下载地址:https://issues.apache.org/jira/secure/attachment/12 ...
- ubuntu安装相关
安装系统参考:http://xinzhi.wenda.so.com/a/1523530837610141 首先进行更新源 sudo apt-get update 安装codeblocks sudo a ...
- python3.6安装jpype1后引入jpype报“ImportError: numpy.core.multiarray failed to import”问题
jpype是调用java接口的第三方库,通过该库,python可以运行java程序,从而解决一些调用java的问题,比如:java开发的接口,测试时, 有java的加密算法就不用python写一遍重复 ...
- [zookeeper]依赖jar的问题
zookeeper是依赖以下三个jar包 log4j-1.2.17.jar slf4j-api-1.7.25.jar slf4j-log4j12-1.7.18.jar 否则会报异常:java.lang ...
- git备份代码
仓库备份位置: /huawei-bak vim /huawei-bak/huawei-bak.sh #!/bin/bash#项目克隆下来后将其注释即可PROJECT="git@codehub ...
- TCP/IP及内核参数优化调优(转)
Linux下TCP/IP及内核参数优化有多种方式,参数配置得当可以大大提高系统的性能,也可以根据特定场景进行专门的优化,如TIME_WAIT过高,DDOS攻击等等.如下配置是写在sysctl.conf ...
- Pyqt5-QtWidget的使用
QTableWidget是QTableViewer的子类 ,其中QTableViewer可以使用自定义的数据模型来显示内容(通过setModel ()来绑定数据源),而QTableWidget提供了一 ...
- C++ 中set
set特点: 所有元素不会重复,重复插入已经有的新值无效: 所有元素按顺序排列:unordered_set除外 键和值相同,所以set中的值是不可更改的 set的各成员函数列表如下: 1.begin( ...
- Apache POI读取Excel
1.pom.xml配置文件 <!-- 配置Apache POI --> <dependency> <groupId>org.apache.poi</group ...