Zookeeper是什么?
1)配置管理,用于分布式系统中加载动态配置,Zookeepe中配置改了,然后服务拿到的就会改变。
有的配置可以更改,有的不可以更改,只能换启动项目以后可以换的服务。
2)名字服务,类似于dnsfuwuqi,解析请求的名字转发到相应的服务。
3)分布式锁,多个进程访问同一资源,谁有锁,谁访问资源。
4)服务发现:每隔一段时间,ping一,次看是否可以查看,是不是挂了,如果挂了zookeeper分配别的,如果没有正常分配。让请求都能找到可用的服务器。
Zookeeper的增删改查
1、首先定义一个全局变量连接地址和超时时间
//zk的连接地址
public static final String zkconnect = "ip地址:2181";
//超时时间
public static final int timeout =15000;
2、连接方法
//连接方法
public static ZooKeeper connect() throws IOException {
ZooKeeper zk = new ZooKeeper(zkconnect,timeout,null);
System.out.println("zk连接成功");
return zk ;
}
3、增
public static void creat(ZooKeeper zooKeeper,String node,String data) throws InterruptedException, KeeperException {
System.out.println("开始创建节点:"+node+"节点数据为:"+data);
List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
CreateMode createMode = CreateMode.PERSISTENT;
zooKeeper.create(node,data.getBytes(),acl,createMode);
System.out.println("zk节点创建成功");
}
4、删
public static void delete(ZooKeeper zooKeeper,String node)throws InterruptedException, KeeperException{
//先查一下节点是否存在
Stat stat = zooKeeper.exists(node,false);
System.out.println("开始删除节点:"+node+"原来的版本号"+stat.getVersion());
zooKeeper.delete(node,stat.getVersion());
System.out.println("zk节点删除成功");
}
5、改
public static void setData(ZooKeeper zooKeeper,String node,String data)throws InterruptedException, KeeperException{
//先查一下节点是否存在
Stat stat = zooKeeper.exists(node,false);
System.out.println("修改节点:"+node+"节点数据为:"+data);
zooKeeper.setData(node,data.getBytes(),stat.getVersion());
System.out.println("zk节点修改成功");
}
6、查
public static void getData(ZooKeeper zooKeeper,String node)throws InterruptedException, KeeperException{
byte[] data = zooKeeper.getData(node,false,null);
System.out.println("查看节点:"+node+"的数据为"+new String(data));
}
7、主函数(主函数就是调用这些方法啦)
public static void main(String[]s)throws IOException,InterruptedException, KeeperException{
ZooKeeper zooKeeper = connect();
creat(zooKeeper,"/myzktest","xiannv");
setData(zooKeeper,"/myzktest","xiaoxiannv");
delete(zooKeeper,"/myzktest");
getData(zooKeeper,"/myzktest");
}