Create Lettuce StatefulRedisConnection for storing string as keys and byte array as value

ⅰ亾dé卋堺 提交于 2019-12-23 02:30:12

问题


I have a Spring boot application which connects to a Redis cluster on AWS. I was trying out Lettuce, and want to create a StatefulRedisConnection for storing keys as string, but values as byte array. I tried using the built-in ByteArrayCodec, but it takes both the key and value as a byte array.

I'm new to Lettuce, so I'm not sure whether I need to write a custom codec. If so, how would I write it? And would there be any performance issues? Or am I going down the wrong path?


回答1:


Below code will allow you to have string key and byte array as value.

public class StringByteCodec implements RedisCodec<String, byte[]> {

    public static final ByteArrayCodec INSTANCE = new ByteArrayCodec();
    private static final byte[] EMPTY = new byte[0];
    private final Charset charset = Charset.forName("UTF-8");

    @Override
    public String decodeKey(final ByteBuffer bytes) {
        return charset.decode(bytes).toString();
    }

    @Override
    public byte[] decodeValue(final ByteBuffer bytes) {
        return getBytes(bytes);
    }

    @Override
    public ByteBuffer encodeKey(final String key) {
        return charset.encode(key);
    }

    @Override
    public ByteBuffer encodeValue(final byte[] value) {
        if (value == null) {
            return ByteBuffer.wrap(EMPTY);
        }

        return ByteBuffer.wrap(value);
    }

    private static byte[] getBytes(final ByteBuffer buffer) {
        final byte[] b = new byte[buffer.remaining()];
        buffer.get(b);
        return b;
    }

}


来源:https://stackoverflow.com/questions/47292145/create-lettuce-statefulredisconnection-for-storing-string-as-keys-and-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!