Spring Boot2.0之 整合Zookeeper叢集
阿新 • • 發佈:2018-11-05
普通的連線:
pom:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.toov5.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.10</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> <exclusion> <artifactId>log4j</artifactId> <groupId>log4j</groupId> </exclusion> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> </dependencies> </project>
程式碼:
package com.toov5.controller; import org.I0Itec.zkclient.ZkClient; public class zkTest { public static void main(String[] args) { String connection = "192.168.91.1:2181,192.168.91.3:2181,192.168.91.4:2181"; ZkClient zkClient = new ZkClient(connection); zkClient.createPersistent("/toov5_01"); zkClient.close(); } }
執行檢視結果:
SpringBoot整合:
配置檔案抽取到 yml中
connection:192.168.91.1:2181,192.168.91.3:2181,192.168.91.4:2181
整合:
package com.toov5.service; import org.I0Itec.zkclient.ZkClient; import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service; @Service public class zkService { @Value("{connection}") private String connection; private ZkClient zkClient = new ZkClient(connection); public String creteNode(String path){ try { zkClient.createPersistent(path); //沒返回結果 所以用try catch 方式解決哦 return "ok"; } catch (Exception e) { return "fail"; } } }
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.toov5.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.10</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> <exclusion> <artifactId>log4j</artifactId> <groupId>log4j</groupId> </exclusion> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>