SpringBoot整合Zookeeper

引入Jar包

复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

<dependency>
	<groupId>org.apache.zookeeper</groupId>
	<artifactId>zookeeper</artifactId>
	<version>3.4.13</version>
</dependency>

<dependency>
	<groupId>org.apache.curator</groupId>
	<artifactId>curator-recipes</artifactId>
	<version>4.1.0</version>
	<exclusions>
		<exclusion>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
		</exclusion>
	</exclusions>
</dependency>

Zookeeper配置

Zookeeper配置连接信息

复制代码
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ZookeeperConfig {

	@Bean("zookeeperClient")
	public CuratorFramework create() {
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
		CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy);
		client.start();
		return client;
	}
}

Zookeeper 的使用

节点监控

复制代码
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.plf.zookeeper.service.NodeService;

@Component
@Order(1)
public class ZookeeperInit implements CommandLineRunner {

	private static final String ROOT_PATH = "/server";

	public TreeCache treeCache;
	
	@Autowired
	private CuratorFramework zookeeperClient;

	@Autowired
	private NodeService nodeService;

	@Override
	public void run(String... args) throws Exception {
		if (!nodeService.isExitNode(ROOT_PATH)) {
			nodeService.createNode(ROOT_PATH);
		}

		// 监视某个节点的数据变化
		treeCache = new TreeCache(zookeeperClient, ROOT_PATH);
		
		treeCache.getListenable().addListener(new TreeCacheListener() {
			@Override
			public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
				ChildData eventData = event.getData();
				switch (event.getType()) {
				case NODE_ADDED:
					System.out.println(eventData.getPath() + "节点添加" + eventData.getPath() + "\t添加数据为:"
							+ new String(eventData.getData()));
					break;
				case NODE_UPDATED:
					System.out.println(eventData.getPath() + "节点数据更新\t更新数据为:" + new String(eventData.getData())
							+ "\t版本为:" + eventData.getStat().getVersion());
					break;
				case NODE_REMOVED:
					System.out.println(eventData.getPath() + "节点被删除");
					break;
				default:
					break;
				}
			}
		});
		
		// 启动监视器对象
		treeCache.start();
	}
}

节点新增

复制代码
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NodeService {

	@Autowired
	private CuratorFramework zookeeperClient;
	
	public void createNode(String nodePath) {
		try {
			zookeeperClient.create().creatingParentsIfNeeded()
				.withMode(CreateMode.PERSISTENT)
				.forPath(nodePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public boolean isExitNode(String path) {
		try {
			Stat stat = zookeeperClient.checkExists().forPath(path);
			if(stat == null) {
				return false;
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}

还有很多其他的方法可以自行扩展。

相关推荐
丘山子几秒前
一些鲜为人知的 IP 地址怪异写法
前端·后端·tcp/ip
CopyLower25 分钟前
在 Spring Boot 中实现 WebSockets
spring boot·后端·iphone
.生产的驴1 小时前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
景天科技苑1 小时前
【Rust】Rust中的枚举与模式匹配,原理解析与应用实战
开发语言·后端·rust·match·enum·枚举与模式匹配·rust枚举与模式匹配
追逐时光者2 小时前
MongoDB从入门到实战之Docker快速安装MongoDB
后端·mongodb
方圆想当图灵2 小时前
深入理解 AOP:使用 AspectJ 实现对 Maven 依赖中 Jar 包类的织入
后端·maven
豌豆花下猫2 小时前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
嘻嘻嘻嘻嘻嘻ys3 小时前
《Spring Boot 3 + Java 17:响应式云原生架构深度实践与范式革新》
前端·后端
异常君3 小时前
线程池隐患解析:为何阿里巴巴拒绝 Executors
java·后端·代码规范
mazhimazhi3 小时前
GC垃圾收集时,居然还有用户线程在奔跑
后端·面试