`
liudunxu2
  • 浏览: 30639 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
文章分类
社区版块
存档分类
最新评论

zkclient中的可复用的一些工具类

 
阅读更多

1.org.I0Itec.zkclient.NetworkUtil,提供获取本机名称,端口是否被占用等功能,其中判断端口是否被占用的代码:

public static boolean isPortFree(int port) {
        try {
            Socket socket = new Socket("localhost", port);
            socket.close();
            return false;
        } catch (ConnectException e) {
            return true;
        } catch (SocketException e) {
            if (e.getMessage().equals("Connection reset by peer")) {
                return true;
            }
            throw new RuntimeException(e);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

2.org.I0Itec.zkclient.serialize.SerializableSerializer,实现ZkSerializer,与TcclAwareObjectIputStream配合,提供java原生的序列化和反序列化的方法,其中TcclAwareObjectIputStream重写了基类ObjectInputStream的resolveClass和resolveProxyClass方法。基类的resolveClass使用的是class.forname,TcclAwareObjectIputStream使用的是
Thread.currentThread().getContextClassLoader();两者的区别可以看一下:http://waryist.iteye.com/blog/131983http://impzx.com/thread-currentthread-getcontextclassloader%EF%BC%88%EF%BC%89%E8%A7%A3%E6%9E%90/
zkclient实现序列换的源码如下:
   @Override
    public Object deserialize(byte[] bytes) throws ZkMarshallingError {
        try {
            ObjectInputStream inputStream = new TcclAwareObjectIputStream(new ByteArrayInputStream(bytes));
            Object object = inputStream.readObject();
            return object;
        } catch (ClassNotFoundException e) {
            throw new ZkMarshallingError("Unable to find object class.", e);
        } catch (IOException e) {
            throw new ZkMarshallingError(e);
        }
    }

    @Override
    public byte[] serialize(Object serializable) throws ZkMarshallingError {
        try {
            ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
            ObjectOutputStream stream = new ObjectOutputStream(byteArrayOS);
            stream.writeObject(serializable);
            stream.close();
            return byteArrayOS.toByteArray();
        } catch (IOException e) {
            throw new ZkMarshallingError(e);
        }
    }


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics