Springboot + zookepper Demo
一、 引入 maven 依赖包, 因为会报有包冲突,所以去掉了slf4j
    <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.7.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-reload4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
二、创建 Zookeeper 客户端的 Bean
import lombok.extern.slf4j.Slf4j; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; import java.util.concurrent.CountDownLatch; @Configuration @Slf4j public class ZkClient { @Value("${zk.hostAddr}") private String zkHostAddr; @Value("${zk.session.timeout:5000}") private Integer sessionTimeOut; @Bean public ZooKeeper zkCli() throws IOException, InterruptedException { final CountDownLatch countDownLatch = new CountDownLatch(1); ZooKeeper zookeeper = new ZooKeeper(zkHostAddr,sessionTimeOut,watchedEvent -> { if(watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected && watchedEvent.getType() == Watcher.Event.EventType.None) { log.info(" 连接成功"); countDownLatch.countDown(); } } ); log.info("连接中..."); countDownLatch.await(); return zookeeper; } }
三、 进行创建操作,获取、修改操作
import lombok.extern.slf4j.Slf4j; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @Slf4j public class ZkOpera { @Autowired private ZooKeeper zkCli; public void createnode() { try { String path = zkCli.create("/sprboot_node", "hello world".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); log.info("created path:{}", path); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public void modifyNode() throws InterruptedException, KeeperException { Stat stat = new Stat(); byte [] data = zkCli.getData("/sprboot_node", false, stat); log.info("修改前数据:{}", new String(data)); zkCli.setData("/sprboot_node","hello doug".getBytes(), stat.getVersion() ); byte [] dataAft = zkCli.getData("/sprboot_node", false, stat); log.info("修改后数据:{}", new String(dataAft)); } }
四、 执行验证
创建: 验证 createnode() 方法

修改: 验证 modifyNode() 方法

 
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号