创建生菜StatefulRedisConnection以将字符串存储为键,将字节数组存储为值

编程入门 行业动态 更新时间:2024-10-24 10:19:00
本文介绍了创建生菜StatefulRedisConnection以将字符串存储为键,将字节数组存储为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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以将字符串存储为键,将字节数组存储为值

本文发布于:2023-10-21 17:26:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1514874.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:生菜   数组   字符串   字节   StatefulRedisConnection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!