Zookeeper分布式管理软件-内容发布
作者:互联网
Zookeeper文件写入
首先必须要关闭虚拟机防火墙,否则写入报错
关闭虚拟机防火墙
systemctl status firewalld--查看防火墙状态,当为runing为打开
systemctl stop firewalld ---临时关闭
systemctl disable firewalld ---永久关闭 ,当为dead则关闭防火墙
当需要打开防火墙时,执行下面语句后重启
systemctl enable firewalld
在zookeeper中创建文件demo,切勿使用自带的zookeeper文件,容易修改原配置
[zk: localhost:2181(CONNECTED) 22] create /demo
Created /demo
注入依赖pom.xml ,版本号和zookeeper版本一致
<!--zookeeper依赖注入-->
<dependencies>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.10</version>
</dependency>
</dependencies>
创建类进行文件写入zookeeper
package com.msb;
import org.apache.zookeeper.*;
import java.io.IOException;
public class MyApp {
public static void main(String[] args){
/**
* 创建zookeeper对象
* 参数1:zookeeper ip+端口号(虚拟机ip,zookeeper端口号)
* 参数2:访问超时设置
* 参数3:连接成功后的编写信息
*/
try {
ZooKeeper zooKeeper = new ZooKeeper("192.168.226.128:2181", 100000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("已连接zookeeper");
}
});
/**
* 参数1:向zookeeper发送的文件
* 参数2:发生的内容
* 参数3:权限
* 参数4:内容的模式
*/
String content = zooKeeper.create("/demo/rim-address","rmi:localhost:8080/demoService".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
}
返回连接成功后的编写信息
在zookeeper中查询发布的内容
[zk: localhost:2181(CONNECTED) 0] ls /
[demo, test, zookeeper]
[zk: localhost:2181(CONNECTED) 2] ls /demo
[rim-address0000000000, rim-address0000000001]
[zk: localhost:2181(CONNECTED) 3] get /demo/rim-address000000000
rim-address0000000000 rim-address0000000001
[zk: localhost:2181(CONNECTED) 4] get /demo/rim-address0000000000
rmi:localhost:8080/demoService
[zk: localhost:2181(CONNECTED) 5]
从zookeeper中获取发布信息,运行后需要等待一段时间,进行数据读取
package com.msb;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.List;
public class SelectApp {
public static void main(String[] args) {
try {
ZooKeeper zookeeper = new ZooKeeper("192.168.226.128:2181", 10000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("获取连接");
}
});
//获取列表
List<String> list = zookeeper.getChildren("/demo", false);
for (String child : list) {
byte[] result = zookeeper.getData("/demo/" + child, false, null);
System.out.println(new String(result));
}
} catch (IOException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
标签:zookeeper,demo,Zookeeper,2181,管理软件,rim,import,localhost,分布式 来源: https://www.cnblogs.com/188221creat/p/16493632.html