Skip to content

Commit

Permalink
optimize zookeeper serialization method
Browse files Browse the repository at this point in the history
  • Loading branch information
zhachen committed Jul 31, 2018
1 parent 042f735 commit e398b76
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.weibo.api.motan.registry.zookeeper;

import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.SerializableSerializer;

import java.io.ObjectStreamConstants;

public class StringSerializer extends SerializableSerializer {
@Override
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
if (getTag(bytes) == ObjectStreamConstants.STREAM_MAGIC) {
return super.deserialize(bytes);
}
return new String(bytes);
}

@Override
public byte[] serialize(Object obj) throws ZkMarshallingError {
return obj.toString().getBytes();
}

private short getTag(byte[] bytes) {
short s = 0;
if (bytes.length > 2) {
for (int i = 0; i < 2; i++) {
s <<= 8;
s |= (bytes[i] & 0x00ff);
}
}
return s;
}
}
Original file line number Diff line number Diff line change
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 e398b76

Please sign in to comment.