问题
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