栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot整合Zookeeper详细教程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot整合Zookeeper详细教程

目录
    • 1.Curator介绍
    • 2.创建springboot项目
    • 3.引⼊Curator
    • 4.application.yml配置⽂件
    • 5.读取配置⽂件注入到容器
    • 6.注⼊CuratorFramework
    • 7.添加测试方法
    • 8.执行测试方法报错解决

注意我这里用的是官方最稳定的版本3.7.1,版本之间有个别命令是有差距的!

本篇文章的示例SpringBoot和Zookeeper客户端以及zookeeper都是最新版本!

1.Curator介绍

Curator是Netflix公司开源的⼀套zookeeper客户端框架,Curator是对Zookeeper⽀持最好的客户端框架。Curator封装了⼤部分Zookeeper的功能,⽐如Leader选举、分布式锁等,减少了技术⼈员在使⽤Zookeeper时的底层细节开发⼯作。

2.创建springboot项目

3.引⼊Curator


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.7.0
		
	
	com.gzl.cn
	spring-boot-curator-zk
	0.0.1-SNAPSHOT
	spring-boot-curator-zk
	Demo project for Spring Boot
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		

        
		
			org.apache.curator
			curator-framework
			5.2.1
		
		 
			org.apache.curator
			curator-recipes
			5.2.1
		
        
        
			org.apache.zookeeper
			zookeeper
			3.8.0
		

		
			org.projectlombok
			lombok
			1.18.22
			provided
		

		
		
			 org.springframework.boot
			 spring-boot-configuration-processor
			 true
		

		
			junit
			junit
			4.12
		
	

	
		
			
				org.apache.maven.plugins
				maven-resources-plugin
				3.1.0
			
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	



4.application.yml配置⽂件

application.yml和application.properties是都可以的,只不过他们的格式不一样。

curator:
  #重试retryCount次,当会话超时出现后,curator会每间隔elapsedTimeMs毫秒时间重试一次,共重试retryCount次。
  retryCount: 5
  elapsedTimeMs: 5000
  #服务器信息
  connectString: 127.0.0.1:2181
  #会话超时时间设置
  sessionTimeoutMs: 60000
  #连接超时时间
  connectionTimeoutMs: 5000
5.读取配置⽂件注入到容器
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "curator")
public class WrapperZK {
    private int retryCount;
    private int elapsedTimeMs;
    private String connectString;
    private int sessionTimeoutMs;
    private int connectionTimeoutMs;
}
6.注⼊CuratorFramework
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CuratorConfig {
    @Autowired
    WrapperZK wrapperZk;

    
    @Bean(initMethod = "start")
    public CuratorFramework curatorFramework() {
        return CuratorFrameworkFactory.newClient(
                wrapperZk.getConnectString(),
                wrapperZk.getSessionTimeoutMs(),
                wrapperZk.getConnectionTimeoutMs(),
                new RetryNTimes(wrapperZk.getRetryCount(), wrapperZk.getElapsedTimeMs()));
    }
}
7.添加测试方法

在这里添加测试方法即可!

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootCuratorZkApplication.class)
class SpringBootCuratorZkApplicationTests {

    @Autowired
    CuratorFramework curatorFramework;

    
    @Test
    void createNode() throws Exception {
        // 添加持久节点
        String path = curatorFramework.create().forPath("/curator-node");
        System.out.println(String.format("curator create node :%s successfully.", path));

        // 添加临时序号节点,并赋值数据
        String path1 = curatorFramework.create()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath("/curator-node", "some-data".getBytes());
        System.out.println(String.format("curator create node :%s successfully.", path));

        // System.in.read()目的是阻塞客户端关闭,我们可以在这期间查看zk的临时序号节点
        // 当程序结束时候也就是客户端关闭的时候,临时序号节点会消失
        System.in.read();
    }

    
    @Test
    public void testGetData() throws Exception {
        // 在上面的方法执行后,创建了curator-node节点,但是我们并没有显示的去赋值
        // 通过这个方法去获取节点的值会发现,当我们通过Java客户端创建节点不赋值的话默认就是存储的创建节点的ip
        byte[] bytes = curatorFramework.getData().forPath("/curator-node");
        System.out.println(new String(bytes));
    }

    
    @Test
    public void testSetData() throws Exception {
        curatorFramework.setData().forPath("/curator-node", "changed!".getBytes());
        byte[] bytes = curatorFramework.getData().forPath("/curator-node");
        System.out.println(new String(bytes));
    }

    
    @Test
    public void testCreateWithParent() throws Exception {
        String pathWithParent = "/node-parent/sub-node-1";
        String path = curatorFramework.create().creatingParentsIfNeeded().forPath(pathWithParent);
        System.out.println(String.format("curator create node :%s successfully.", path));
    }

    
    @Test
    public void testDelete() throws Exception {
        String pathWithParent = "/node-parent";
        curatorFramework.delete().guaranteed().deletingChildrenIfNeeded().forPath(pathWithParent);
    }
}
8.执行测试方法报错解决


上面那个闪电意思是install的时候跳过maven测试阶段,之所以要跳过测试阶段是因为假如不跳过他会验证测试方法,例如我们创建节点的方法,有时候我们节点已经创建了,但是他还会验证,所以就会报错。

源码地址:https://gitee.com/gzl_com/spring-cloud.git

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/996909.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号