用string作為key,用byte[]作為value
請問改如何用RedisTemplate來實作?
本來是想,寫一個spring redis的決議類,可將protobuf message與其對應的byte[]轉換

但我發現貌似不可以,protobuf message的抽象父類GeneratedMessage以及實作的介面MessageOrBuilder中都不含有parseFrom的函式
不知哪位高手有啥辦法。
或者,實在不行,我該怎么寫這個決議類或者啥辦法能實作我用string作為key,用byte[]作為value來操作讀取、寫入由protobuf序列化為的byte[]
uj5u.com熱心網友回復:
哎,單獨寫一個存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;
}
}
uj5u.com熱心網友回復:
你key也是byte陣列不就行了,為什么一定要stringuj5u.com熱心網友回復:
這個問題也不難在序列化的時候,在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 內容體
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/70508.html
標籤:Java EE
上一篇:PC QQ協議 decodekey怎么獲取求大佬指點
下一篇:tomcat專案部署問題
