Python和Java,文件和Redis之间有一些字节转换:
是因为Python的Redis set()是另一种字节字符集吗?我不知道。请帮助我。
redis_conn = redis.Redis(
host=RedisHost,
port=RedisPort,
password=RedisPass,
db=0
)
key = 'key'
value = open('bytes_file', 'rb').read()
redis_conn.set(key, value)
@Autowired
private RedisTemplate<String, byte[]> redis;
public void readRedis() {
String key = "key";
redis.boundValueOps(key).get(); // exception
}
org.springframework.data.redis.serializer.SerializationException: Cannot deserialize;
nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?;
nested exception is java.io.StreamCorruptedException: invalid stream header: 789CED9D
答案 0 :(得分:0)
这是因为Spring-Redis具有默认的valueSerializer
,它将序列化原始byte[]
。
byte[] rawValue(Object value) {
if (valueSerializer() == null && value instanceof byte[]) {
return (byte[]) value;
}
return valueSerializer().serialize(value);
}
因此将Serializer
设置为null
可解决此问题
@Bean
public RedisTemplate<byte[], byte[]> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// set this false will keep all Serializer null
template.setEnableDefaultSerializer(false);
return template;
}