Spring Cloud Zookeeper 的作用
zookeeper是对分布式服务提供协调服务的apache开源项目。具体原理在上一讲中《SpringCloud学习笔记七:Spring Cloud Zookeeper 服务管理》都具体描述过,这一讲我们话不多说,直接上代码。
本次实战基于springcloud zookeeper进行开发,具体pom文件添加如下内容
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-config</artifactId>
</dependency>
以及springcloud的版本管理
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
创建测试类,具体逻辑在测试类中体现
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class ZookeeperApplicationTests {
String connectString = "127.0.0.1:2181";
int sessionTimeout = 2000;
private ZooKeeper zooCli;
/**
* 创建zookeeper服务
*
* @throws IOException
*/
@Before
public void init() throws IOException {
zooCli = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
List<String> children = null;
try {
children = zooCli.getChildren("/", true);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (String child : children) {
System.out.println(child);
}
System.out.println("-----------------");
}
});
}
/**
* 创建节点
*
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void createNode() throws KeeperException, InterruptedException {
String path = zooCli.create("/bbb", "bruce is handsome".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(path);
}
/**
* 监听节点状态,实际监听逻辑已经迁移到创建zookeeper服务方法中
*
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void getDataAndWatch() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}
/**
* 判断zookeeper节点是否存在
*
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void exist() throws KeeperException, InterruptedException {
Stat stat = zooCli.exists("/bruce", false);
System.out.println(stat == null ? "not exist" : "exist");
}
}
在测试前,我们需要启动zookeeper的服务端,不然代码中监听不到zookeeper服务,代码会报错。