普通的连接:
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>
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/16139.html