1.创建测试项目,注入pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 自定义zookeeper组件加入进来 -->
<dependency>
<groupId>com.cc</groupId>
<artifactId>foundation-zookeeper</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
2.添加配置文件application.properties:
server.context-path=/
server.port=8001
zookeeper.address=192.168.1.11:2182,192.168.1.11:2183,192.168.1.11:2184
zookeeper.sessionTimeout=10000
zookeeper.connectionTimeout=10000
3.创建IndexController:
package com.cc.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cc.service.LisenterService;
import com.cc.zookeeper.api.ZookeeperClient;
@RestController
public class IndexController {
@Autowired
private ZookeeperClient client;
@Autowired
private LisenterService lisenterService;
@RequestMapping("/index")
public String index() throws Exception{
return "zk-test";
}
@RequestMapping("/insert")
public String insert() throws Exception{
client.addPersistentNode("/super", "parent_node");
return "insert success!";
}
//启动watcher,监听节点
@RequestMapping("/watcher")
public String watcher() throws Exception{
client.listener4ChildrenPath("/super", lisenterService);;
return "watcher success!";
}
//添加子节点,查看监听是否调用方法发送通知
@RequestMapping("/insertparent")
public String insertc1() throws Exception{
client.addPersistentNode("/super/c1", "c1 data");
return "insert success!";
}
}
4.创建LisenterService用来实现NodeListener:
package com.cc.service;
import org.springframework.stereotype.Component;
import com.cc.zookeeper.api.ChangedEvent;
import com.cc.zookeeper.api.NodeListener;
import com.cc.zookeeper.api.ZookeeperClient;
/**
* watcher机制:
* 实现NodeListener接口
*
*/
@Component
public class LisenterService implements NodeListener{
@Override
public void nodeChanged(ZookeeperClient client, ChangedEvent event) throws Exception {
System.out.println("收到通知:节点路径为:"+event.getPath()+",节点内容:"+event.getData()+"变更操作为:"+event.getType());
}
}
启动测试:
在地址栏输入:
http://localhost:8001/index //结果:测试服务引入正常
http://localhost:8001/insert //结果:添加节点正常
http://localhost:8001/watcher //结果:watcher 启动
http://localhost:8001/insertparent
至此zookeeper基础功能封装注入完成!
由于组件封装篇幅过长,所以分为三篇来写,请结合上两篇一起看;