com.github.linshenkx.rpcnettycommon.serialization.serializer.impl.ThriftSerializer Maven / Gradle / Ivy
package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;
import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
import org.apache.thrift.TBase;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TBinaryProtocol;
/**
* @version V1.0
* @author: lin_shen
* @date: 2018/11/18
* @Description: Thrift序列化(只能序列化IDL产生的类)
*/
public class ThriftSerializer implements ISerializer {
@Override
public byte[] serialize(T obj) {
try {
TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
return serializer.serialize((TBase) obj);
} catch (TException e) {
throw new RuntimeException(e);
}
}
@Override
public T deserialize(byte[] data, Class clazz) {
try {
TBase o = (TBase) clazz.newInstance();
TDeserializer tDeserializer = new TDeserializer();
tDeserializer.deserialize(o, data);
return (T) o;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}