Skip to content

Commit

Permalink
Merge pull request #732 from Zha-Zha/feature/zkSerialize
Browse files Browse the repository at this point in the history
Optimize zookeeper serialization method
  • Loading branch information
rayzhang0603 committed Aug 13, 2018
2 parents c3cb63a + d21c36a commit 82976fa
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
@@ -1,6 +1,7 @@
package com.weibo.utils;

import com.weibo.api.motan.exception.MotanFrameworkException;
import com.weibo.api.motan.registry.zookeeper.StringSerializer;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
Expand All @@ -22,7 +23,7 @@ public class ZkClientWrapper {
@PostConstruct
void init() {
try {
zkClient = new ZkClient(registryUrl, 10000);
zkClient = new ZkClient(registryUrl, 10000, 10000, new StringSerializer());
} catch (Exception e) {
throw new MotanFrameworkException("Fail to connect zookeeper, cause: " + e.getMessage());
}
Expand Down
@@ -0,0 +1,31 @@
package com.weibo.api.motan.registry.zookeeper;

import com.weibo.api.motan.util.ByteUtil;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.SerializableSerializer;

import java.io.ObjectStreamConstants;
import java.io.UnsupportedEncodingException;

public class StringSerializer extends SerializableSerializer {
@Override
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
try {
if (ByteUtil.bytes2short(bytes, 0) == ObjectStreamConstants.STREAM_MAGIC) {
return super.deserialize(bytes);
}
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError(e);
}
}

@Override
public byte[] serialize(Object obj) throws ZkMarshallingError {
try {
return obj.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError(e);
}
}
}
Expand Up @@ -27,15 +27,14 @@

@SpiMeta(name = "zookeeper")
public class ZookeeperRegistryFactory extends AbstractRegistryFactory {

@Override
protected Registry createRegistry(URL registryUrl) {
try {
int timeout = registryUrl.getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue());
int sessionTimeout =
registryUrl.getIntParameter(URLParamType.registrySessionTimeout.getName(),
URLParamType.registrySessionTimeout.getIntValue());
ZkClient zkClient = new ZkClient(registryUrl.getParameter("address"), sessionTimeout, timeout);
ZkClient zkClient = new ZkClient(registryUrl.getParameter("address"), sessionTimeout, timeout, new StringSerializer());
return new ZookeeperRegistry(registryUrl, zkClient);
} catch (ZkException e) {
LoggerUtil.error("[ZookeeperRegistry] fail to connect zookeeper, cause: " + e.getMessage());
Expand Down

0 comments on commit 82976fa

Please sign in to comment.