Py学习  »  Redis

Python将字节写入ReDIS,但Java以异常方式读取它。

Archon • 4 年前 • 356 次点击  

Python和Java、文件和Redis之间有一些字节转换:

  1. 文件:Python Wrad(),Java Read()。(好)
  2. 文件:Java写(),Python Read()。(好)
  3. RyIs:Python Stand(),Java GET()。(错误)
  4. RIDIS:Java Stand(),pTyHon GET()。(好)

是因为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)

Java部分

@Autowired
private RedisTemplate<String, byte[]> redis;

public void readRedis() {
    String key = "key";
    redis.boundValueOps(key).get(); // exception
}

Java异常

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/37887
 
356 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Archon
Reply   •   1 楼
Archon    5 年前

因为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;
}