如何用RedisTemplate存储读取byte[](由protobuf序列化为的byte[]) ?

qiuzhizhe8888 2018-04-06 12:00:29
用string作为key,用byte[]作为value

请问改如何用RedisTemplate来实现?

本来是想,写一个spring redis的解析类,可将protobuf message与其对应的byte[]转换


但我发现貌似不可以,protobuf message的抽象父类GeneratedMessage以及实现的接口MessageOrBuilder中都不含有parseFrom的函数

不知哪位高手有啥办法。

或者,实在不行,我该怎么写这个解析类或者啥办法能实现我用string作为key,用byte[]作为value来操作读取、写入由protobuf序列化为的byte[]
...全文
4752 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
GeTOUO 2020-05-14
  • 打赏
  • 举报
回复
这个问题也不难 在序列化的时候,在protobuf实例的前面加上一个该消息的类型,再加一个包头用来分隔类型和内容:

serialize(T t) {
    byte[] clzBytes = t.getClass().toString().getBytes(); // 将存储的protobuf实际类型取出并序列化
        byte[] contentBytes = t.toByteArray(); // 内容序列化

        byte[] fullPacket = Arrays.copyOf(new byte[]{((Integer) clzBytes.length).byteValue()}, 1 + clzBytes.length + contentBytes.length);
        System.arraycopy(clzBytes, 0, fullPacket, 1, clzBytes.length);
        System.arraycopy(contentBytes, 0, fullPacket, 1 + clzBytes.length, contentBytes.length);

        return fullPacket;
}
然后在解码的时候,先解第一个字节获取得到 class 的长度,在解class的类型,在通过class反射实例parseFrom 内容体
eeetttzhangji 2019-12-02
  • 打赏
  • 举报
回复
你key也是byte数组不就行了,为什么一定要string
qiuzhizhe8888 2018-04-06
  • 打赏
  • 举报
回复
哎,单独写一个存byte[]的解析器倒是可以解决这个问题。但请各位高手指点,有没有啥办法能实现我想要的,上面那种直接protubuf类到byte[]直接在解析器中转换好?
public class ByteRedisSerializer implements RedisSerializer<byte[]> {
	private final Charset charset;

	public ByteRedisSerializer() {
		this(Charset.forName("UTF8"));
	}

	public ByteRedisSerializer(Charset charset) {
		Assert.notNull(charset, "Charset must not be null!");
		this.charset = charset;
	}

	@Override
	public byte[] serialize(byte[] t) throws SerializationException {
		return t;
	}

	@Override
	public byte[] deserialize(byte[] bytes) throws SerializationException {
		return bytes;
	}

}

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧