All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.linshenkx.rpcnettycommon.serialization.serializer.impl.AvroSerializer Maven / Gradle / Ivy

package com.github.linshenkx.rpcnettycommon.serialization.serializer.impl;




import com.github.linshenkx.rpcnettycommon.serialization.serializer.ISerializer;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @version V1.0
 * @author: lin_shen
 * @date: 2018/11/18
 * @Description: AvroSerializer(只能序列化IDL产生的类)
 */
public class AvroSerializer implements ISerializer {


    @Override
    public  byte[] serialize(T obj) {
        try {
            DatumWriter userDatumWriter = new SpecificDatumWriter(obj.getClass());
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            BinaryEncoder binaryEncoder = EncoderFactory.get().directBinaryEncoder(outputStream, null);
            userDatumWriter.write(obj, binaryEncoder);
            return outputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public  T deserialize(byte[] data, Class clazz) {
        try {
            DatumReader userDatumReader = new SpecificDatumReader(clazz);
            BinaryDecoder binaryDecoder = DecoderFactory.get().directBinaryDecoder(new ByteArrayInputStream(data), null);
            return (T) userDatumReader.read(clazz.newInstance(), binaryDecoder);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy