我正在使用jedis
从redis
获取数据。
jedis.hgetall
返回我要反序列化的Map<byte[], byte[]>
。
对于其他redis操作(如hget),我可以使用SerializationUtils.deserialize(byte[] objectData)
轻松反序列化,因为它们会返回byte[]
。
知道如何反序列化byte[]
的地图?
答案 0 :(得分:0)
你可以在下面的menthods中找到你想要的反序列化方法:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class SerializeUtil {
/**
* unserialize byte[]
* @param bytes
* @return Object
*/
public static Object unserialize(final byte[] bytes) {
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
}
return null;
}
/**
* unserialize hash Map<byte[], byte[]>
* @param hash
* @return Map<Object, Object>
*/
public static Map<Object, Object> unserializehmbb2moo(final Map<byte[], byte[]> hash) {
Map<Object, Object> result = new HashMap<Object, Object>();
try {
Set<byte[]> keys = hash.keySet();
if (keys != null && keys.size() > 0) {
for (byte[] key : keys) {
result.put(unserialize(key), unserialize(hash.get(key)));
}
}
} catch (Exception e) {
}
return result;
}
/**
* unserialize hash Map<byte[], byte[]>
* @param hash
* @return Map<String, Object>
*/
public static Map<String, Object> unserializehmbb2mso(final Map<byte[], byte[]> hash) {
Map<String, Object> result = new HashMap<String, Object>();
try {
Set<byte[]> keys = hash.keySet();
if (keys != null && keys.size() > 0) {
for (byte[] key : keys) {
result.put(unserialize(key).toString(), unserialize(hash.get(key)));
}
}
} catch (Exception e) {
}
return result;
}
}
答案 1 :(得分:0)
使用基于Redis的框架 - Redisson:
,您可以轻松完成Config config = new Confing();
config.setCodec(new SerializationCodec());
RedissonClient redisson = Redisson.create(config);
Map<MyKey, MyObject> map = redisson.getMap("myMap");
// both key and value objects are serialized transparently
map.put(new MyKey(), new MyObject());
// value object is deserialized transparently
map.get(new MyKey());
它提供了大量的编解码器,例如Jackson JSON
,Avro
,Amazon Ion
,Smile
,CBOR
,MsgPack
,{{1} },Kryo
,FST
,LZ4
和Snappy
,让您专注于业务逻辑开发,而不是使用Jedis进行序列化和连接处理......