netty實現(xiàn)Object的傳輸

當(dāng)我們利用protobuf傳輸?shù)臅r候,我們需要定義.proto文件,再利用protobuf插件生成java類型。這是有點麻煩,有沒有直接就可以轉(zhuǎn)換的方法呢?當(dāng)然是有的,protostudff提供了可以直接價格Object傳輸?shù)姆椒?,只要提供這個類的Schema。

 <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.32.Final</version>
        </dependency>

        <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java</artifactId>
        <version>${protobuf.version}</version>
        </dependency>
      <dependency>
            <groupId>io.protostuff</groupId>
            <artifactId>protostuff-core</artifactId>
            <version>1.6.0</version>
        </dependency>

        <dependency>
            <groupId>io.protostuff</groupId>
            <artifactId>protostuff-runtime</artifactId>
            <version>1.6.0</version>
        </dependency>
        <!-- 用來new一個新類-->
        <dependency>
            <groupId>org.objenesis</groupId>
            <artifactId>objenesis</artifactId>
            <version>2.6</version>
        </dependency>
import java.util.concurrent.ConcurrentHashMap;

public class SerializationUtil {
    private static final ConcurrentHashMap<Class<?>, Schema<?>> map = new ConcurrentHashMap<>();
    private static final LinkedBuffer linkedBuffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    private static  final  Objenesis objenesis= new ObjenesisStd();
    public  static <T> byte[] serialize(T obj){
        Class<?> aClass = obj.getClass();
        Schema schema = getSchema(aClass);
        byte[] data;
        try {

            data = ProtobufIOUtil.toByteArray(obj, schema, linkedBuffer);
        }finally {
            linkedBuffer.clear();
        }
        return  data;
    }
    public static <T>  T deserialize(byte[] bytes,Class<T> clazz){
        try {
            Schema schema = getSchema(clazz);
            T o = objenesis.newInstance(clazz);
            ProtobufIOUtil.mergeFrom(bytes, o, schema);
            return  o;
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;

    }
    private static Schema getSchema(Class clazz){
        Schema<?> schema = map.get(clazz);
        if(schema==null){
            schema= RuntimeSchema.getSchema(clazz);
            if(schema!=null){
                map.put(clazz,schema);
            }
        }
        return schema;
    }

}

編解碼器

public class ObjDecoder extends ByteToMessageDecoder {
    private Class<?> clazz;
   public  ObjDecoder(Class clazz){
        this.clazz=clazz;
    }
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

       if(in.readableBytes()<4){
           return;
       }
       in.markReaderIndex();
       int mslength= in.readInt();
       if(in.readableBytes()<mslength){
           in.resetReaderIndex();
           return;
       }
       byte[] data= new byte[mslength];
       in.readBytes(data);
       out.add(SerializationUtil.deserialize(data,clazz));
    }
}
public class ObjEncoder extends MessageToByteEncoder {
    private Class<?> genericClass;
   public ObjEncoder(Class<?> genericClass){
        this.genericClass=genericClass;
    }
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
                if(genericClass.isInstance(msg)){
                    byte[] serialize = SerializationUtil.serialize(msg);
                    out.writeInt(serialize.length);
                    out.writeBytes(serialize);
                }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容