java操作zookeeper
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java操作zookeeper相关的知识,希望对你有一定的参考价值。
package com.ikilun.web.controller; import java.io.IOException; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ZookeeperClientController { private String HOST = "192.168.100.108:2181"; private int sessionTimeout = 3000; private ZooKeeper zk; private void initZk() { try { zk = new ZooKeeper(HOST, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { String path = event.getPath(); System.out.println("watch:" + event.getType() + ",path:" + path); } }); } catch (IOException e) { e.printStackTrace(); } } //新建znode节点 @RequestMapping("/zk/create") public String create(String path, String data) { if (zk == null) { initZk(); } try { String result = zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); return result; } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } return "failure"; } //get znode节点数据 @RequestMapping("/zk/get") public String get(String path) { if (zk == null) { initZk(); } String result = null; try { byte[] bytes = zk.getData(path, null, null); result = new String(bytes); } catch (Exception e) { e.printStackTrace(); } return result; } //set znode节点数据 @RequestMapping("/zk/set") public String set(String path, String data) { if (zk == null) { initZk(); } try { Stat stat = zk.setData(path, data.getBytes(), -1); return stat.toString(); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } return "failure"; } //delete znode @RequestMapping("/zk/delete") public String delete(String path) { if (zk == null) { initZk(); } try { zk.delete(path, -1); } catch (InterruptedException | KeeperException e) { e.printStackTrace(); } return "success"; } }
以上是关于java操作zookeeper的主要内容,如果未能解决你的问题,请参考以下文章