Quarkus Redis缓存存储Protobuf对象,value-type配置咨询
Quarkus Redis缓存Protobuf对象的value-type配置方案
针对你遇到的问题,有两种直接可行的配置方案,无需通过String中转:
方案1:使用Protobuf的ByteString类型
配置quarkus.cache.redis.value-type为com.google.protobuf.ByteString,这是Protobuf官方提供的字节容器类,本身实现了Serializable接口,完全符合Quarkus Redis缓存的序列化要求。
配置示例:
quarkus.cache.redis.value-type=com.google.protobuf.ByteString
使用时直接将Protobuf对象转为ByteString存入缓存:
@CacheResult(cacheName = "proto-cache") public ByteString getCachedProto(String key) { // 从数据源获取Protobuf对象 MyProtobufObject protoObj = fetchData(key); // 转为ByteString返回,自动存入缓存 return protoObj.toByteString(); }
方案2:使用原生byte数组
如果偏好使用原生byte[],需要配置数组的合法类名标识——Java中byte数组的类名是[B(可通过byte[].class.getName()验证),而非直接写byte[]。
配置示例:
quarkus.cache.redis.value-type=[B
使用时返回Protobuf对象的字节数组即可:
@CacheResult(cacheName = "proto-cache") public byte[] getCachedProtoBytes(String key) { MyProtobufObject protoObj = fetchData(key); return protoObj.toByteArray(); }
为什么之前配置byte[]报错?
Quarkus的配置要求value-type必须是合法的全限定类名字符串,而byte[]并不是标准的类名格式。Java中数组的类名采用特殊标识:前缀[加类型代码,byte对应的代码是B,因此[B才是byte数组的合法类名表示。
内容的提问来源于stack exchange,提问作者GeauxEric
相关产品推荐
相关产品推荐

