spring redis 캐 시 kryo 로 직렬 화

2092 단어 Javaspringredis

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());
            }
        };
    }
}

좋은 웹페이지 즐겨찾기