#===利用byte[]和ObjectOutputStream 、ObjectInputStream============>将对象序列化到zookeeper
HostAndThreadNumss hostAndThreadNum_send = new HostAndThreadNumss("hadoop1",3);
byte[] bt = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(hostAndThreadNum_send);
bt = byteArrayOutputStream.toByteArray();
//以二进制数组的形式,存到zookeeper上
zk.create("/testObject", bt, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
#===>将zookeeper中的序列化对象转化成本地的对象。
bt = zk.getData("/testObject", null, null);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bt);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
HostAndThreadNumss hostAndThreadNum_recevi = (HostAndThreadNumss) objectInputStream.readObject();
System.out.println(hostAndThreadNum_recevi.getHost()+ " " + hostAndThreadNum_recevi.getThreadNum());
#========利用fastjson实现=======>将对象通过fastjson工具转化为json字符串,然后发送到zookeeper
HostAndThreadNumss hostAndThreadNum_send = new HostAndThreadNumss("hadoop1",3);
String MyObjectStr = JSON.toJSONString(hostAndThreadNum_send);//这就相当于Serializable
//以二进制数组的形式,存到zookeeper上
zk.create("/MyObjectStr", MyObjectStr.getBytes("utf-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
===>将json字符串从zookeeper上下载下来。
String recevi_jsonStr = new String(zk.getData("/MyObjectStr", null, null));
HostAndThreadNumss hostAndThreadNum_recevi =
JSON.parseObject(recevi_jsonStr, HostAndThreadNumss.class);
System.out.println(hostAndThreadNum_recevi.getHost() + " " + hostAndThreadNum_recevi.getThreadNum());
#总结:
zookeeper上面存储的是字节数组byte[],而任何的信息都可以转化为byte[],所以只要将信息转化为字节数组,都可以往上面存储,需要还原的时候就取回来。自己通过相应的方法进行转化即可。
将对象转化为json字符串很方便,而且转化后非常的小,有利于网络传输 而ObjectOutputStream 这种序列化会使得byte[]非常的大,大好多倍,不利于传输和存储。