spring redis 缓存使用kryo做序列化


import java.nio.ByteBuffer;

import org.springframework.data.redis.serializer.RedisElementReader;
import org.springframework.data.redis.serializer.RedisElementWriter;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
import org.springframework.stereotype.Component;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.ByteBufferInputStream;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoPool;

@Component
public class KryoObjectSerializer implements SerializationPair {
    /** Kryo池 */
    KryoPool kryoPool = new KryoPool.Builder(Kryo::new).build();

    private Kryo getKryo() {
        Kryo kryo = kryoPool.borrow();
        // 设置类加载器,应对ClassCastException异常
        // 如果不设置的话,使用spring-boot-devtools时,会抛异常
        kryo.setClassLoader(getClass().getClassLoader());
        return kryo;
    }

    @Override
    public RedisElementReader getReader() {
        return new RedisElementReader() {
            @Override
            public Object read(ByteBuffer buffer) {
                Kryo kryo = getKryo();
                try {
                    return kryo.readClassAndObject(
                            new Input(new ByteBufferInputStream(buffer)));
                } finally {
                    kryoPool.release(kryo);
                }
            }
        };
    }

    @Override
    public RedisElementWriter getWriter() {
        return new RedisElementWriter() {
            @Override
            public ByteBuffer write(Object element) {
                Kryo kryo = getKryo();
                Output output = new Output(1024, 1024 * 100);
                try {
                    kryo.writeClassAndObject(output, element);
                } finally {
                    kryoPool.release(kryo);
                }
                return ByteBuffer.wrap(output.getBuffer());
            }
        };
    }
} 
  

 

你可能感兴趣的:(Java,spring,redis)