007 zookeeper基础组件封装-核心原理测试

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基础功能封装注入完成!

由于组件封装篇幅过长,所以分为三篇来写,请结合上两篇一起看;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值