基于Curator操作ZooKeeper(三)-Curator整合Spring

Java原生API操作ZooKeeper可参看:

Java原生API操作Zookeeper(一)

Java原生API操作Zookeeper(二)

相关内容:

基于Curator操作ZooKeeper(一)-基本操作

基于Curator操作ZooKeeper(二)-Watcher操作-补充TreeCache

基于Curator操作ZooKeeper(二)-Watcher操作

 

Curator整合Spring和Spring Boot方式都是差不多的。

在Spring项目中引入依赖:

       <!-- <dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>3.4.11</version>

		</dependency>  -->

		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-framework</artifactId>
			<version>4.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-recipes</artifactId>
			<version>4.0.0</version>
		</dependency>

增加applicationContext-xx.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    <description>ZK与Spring整合,启动项目时建立与ZK的连接</description>
    <!--ZK重试策略-->
    <bean id="retryPolicy" class="org.apache.curator.retry.RetryNTimes">
        <!--重试次数-->
        <constructor-arg index="0" value="10"/>
        <!--每次间隔ms-->
        <constructor-arg index="1" value="5000"/>
    </bean>

    <!--ZK客户端-->
    <bean id="client" class="org.apache.curator.framework.CuratorFrameworkFactory" factory-method="newClient"
          init-method="start">
        <!--ZK服务地址,集群使用逗号分隔-->
        <constructor-arg index="0" value="192.168.220.136,192.168.220.137"/>
        <!--session timeout会话超时时间-->
        <constructor-arg index="1" value="10000"/>
        <!--ConnectionTimeoutMs创建连接超时时间-->
        <constructor-arg index="2" value="5000"/>
        <!--重试策略-->
        <constructor-arg index="3" ref="retryPolicy"/>
    </bean>

    <!--扩展注入ZK工具-->
    <bean id="zkCurator" class="dongguabai.ZKCurator" init-method="init">
        <constructor-arg index="0" ref="client"/>
    </bean>
</beans>

ZK客户端:

package dongguabai;

import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Dongguabai
 * @date 2018/10/18 15:12
 */
public class ZKCurator {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZKCurator.class);

    //ZK客户端
    private CuratorFramework client = null;

    public ZKCurator(CuratorFramework client) {
        this.client = client;
    }

    /**
     * 初始化操作
     */
    public void init(){
        //使用命名空间
        client  = client.usingNamespace("testDgb");
    }

    /**
     * 判断ZK是否连接
     * @return
     */
    public boolean isZKAlive(){
        return client!=null && client.isStarted();
    }
}

测试:

import dongguabai.ZKCurator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 两景Controller
 * @author Dongguabai
 * @date 2018/10/9 16:35
 */
@RestController
@RequestMapping("twoScenes")
public class ZJTwoScenesController extends BaseController{
    //todo 预留的两景Controller

    @Autowired
    private ZKCurator zkCurator;

    @RequestMapping("/check")
    public Object check(){
        return ResultHelper.success(zkCurator.isZKAlive()?"已连接":"断开");
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring整合Zookeeper,你可以按照以下步骤进行操作: 1. 添加Zookeeper依赖:在你的Spring项目的pom.xml文件中添加Zookeeper依赖。例如,使用Apache Curator作为Zookeeper客户端,可以添加以下依赖: ```xml <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>4.2.0</version> </dependency> ``` 2. 创建Zookeeper客户端:在你的Spring配置文件中,创建一个Zookeeper客户端的Bean,以连接到Zookeeper服务器。你可以配置Zookeeper连接的相关属性,例如Zookeeper服务器的地址、会话超时时间等。 ```java @Bean public CuratorFramework curatorFramework() { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy); curatorFramework.start(); return curatorFramework; } ``` 3. 使用Zookeeper:现在你可以在你的Spring应用程序中使用Zookeeper了。例如,你可以创建一个Zookeeper节点、读取节点数据或监视节点的变化。 ```java @Autowired private CuratorFramework curatorFramework; public void createNode(String path, byte[] data) throws Exception { curatorFramework.create().creatingParentsIfNeeded().forPath(path, data); } public byte[] getNodeData(String path) throws Exception { return curatorFramework.getData().forPath(path); } public void watchNode(String path) throws Exception { NodeCache nodeCache = new NodeCache(curatorFramework, path); nodeCache.start(); nodeCache.getListenable().addListener(() -> { ChildData childData = nodeCache.getCurrentData(); if (childData != null) { System.out.println("Node data changed: " + new String(childData.getData())); } }); } ``` 这样,你就可以在Spring中实现与Zookeeper的集成。通过Curator Framework提供的API,可以方便地操作Zookeeper节点,并响应节点数据的变化。记得根据你项目的实际需要进行相应的配置和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值