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

com.github.xiaolyuh.serializer.KryoRedisSerializer Maven / Gradle / Ivy

package com.github.xiaolyuh.serializer;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.github.xiaolyuh.support.NullValue;
import com.github.xiaolyuh.support.SerializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.io.ByteArrayOutputStream;

/**
 * @param  T
 * @author yuhao.wang
 */
public class KryoRedisSerializer implements RedisSerializer {
    Logger logger = LoggerFactory.getLogger(KryoRedisSerializer.class);
    private static final ThreadLocal kryos = ThreadLocal.withInitial(Kryo::new);

    private Class clazz;

    public KryoRedisSerializer(Class clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return SerializationUtils.EMPTY_ARRAY;
        }

        Kryo kryo = kryos.get();
        // 设置成false 序列化速度更快,但是遇到循环应用序列化器会报栈内存溢出
        kryo.setReferences(false);
        kryo.register(clazz);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             Output output = new Output(baos)) {
            kryo.writeClassAndObject(output, t);
            output.flush();
            return baos.toByteArray();
        } catch (Exception e) {
            logger.error("KryoRedisSerializer 序列化异常: {}", e.getMessage(), e);
            throw new SerializationException("KryoRedisSerializer 序列化异常: " + e.getMessage(), e);
        } finally {
            kryos.remove();
        }
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (SerializationUtils.isEmpty(bytes)) {
            return null;
        }

        Kryo kryo = kryos.get();
        // 设置成false 序列化速度更快,但是遇到循环应用序列化器会报栈内存溢出
        kryo.setReferences(false);
        kryo.register(clazz);

        try (Input input = new Input(bytes)) {

            Object result = kryo.readClassAndObject(input);
            if (result instanceof NullValue) {
                return null;
            }
            return (T) result;
        } catch (Exception e) {
            logger.error("KryoRedisSerializer 反序列化异常: {}", e.getMessage(), e);
            throw new SerializationException("KryoRedisSerializer 反序列化异常: " + e.getMessage(), e);
        } finally {
            kryos.remove();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy