我有一个Spring boot应用程序,该应用程序连接到AWS上的Redis集群.我正在尝试生菜,并想创建一个StatefulRedisConnection来将键存储为字符串,但将值存储为字节数组.我尝试使用内置的ByteArrayCodec,但是它将键和值都作为字节数组.
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.
我是Lettuce的新手,所以不确定是否需要编写自定义编解码器.如果是这样,我该怎么写?会不会有性能问题?还是我走错了路?
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?
推荐答案下面的代码将允许您将字符串键和字节数组作为值.
Below code will allow you to have string key and byte array as value.
public class StringByteCodec implements RedisCodec<String, byte[]> { public static final StringByteCodec INSTANCE = new StringByteCodec(); 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; } }更多推荐
创建生菜StatefulRedisConnection以将字符串存储为键,将字节数组存储为值
发布评论