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

com.xxl.rpc.serialize.impl.ProtostuffSerializer Maven / Gradle / Ivy

package com.xxl.rpc.serialize.impl;

import com.xxl.rpc.serialize.Serializer;
import com.xxl.rpc.util.XxlRpcException;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Protostuff util
 * xuxueli 2015-10-29 18:53:43
 */
public class ProtostuffSerializer extends Serializer {

    private static Objenesis objenesis = new ObjenesisStd(true);
    private static Map, Schema> cachedSchema = new ConcurrentHashMap, Schema>();

    private static  Schema getSchema(Class cls) {
        @SuppressWarnings("unchecked")
		Schema schema = (Schema) cachedSchema.get(cls);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(cls);
            if (schema != null) {
                cachedSchema.put(cls, schema);
            }
        }
        return schema;
    }
    
    @Override
	public  byte[] serialize(T obj) {
    	@SuppressWarnings("unchecked")
		Class cls = (Class) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema schema = getSchema(cls);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new XxlRpcException(e);
        } finally {
            buffer.clear();
        }
	}

	@Override
	public  Object deserialize(byte[] bytes, Class clazz) {
		try {
            T message = (T) objenesis.newInstance(clazz);
            Schema schema = getSchema(clazz);
            ProtostuffIOUtil.mergeFrom(bytes, message, schema);
            return message;
        } catch (Exception e) {
            throw new XxlRpcException(e);
        }
	}
    
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy