Q: Python write bytes to Redis but Java read it with exception There are some bytes transitions between Python and Java, File and Redis:  


*

*File:  Python write(), Java read(). (OK)

*File:  Java write(), Python read(). (OK)

*Redis: Python set(), Java get(). (ERROR)

*Redis: Java set(), Ptyhon get(). (OK)


Is it because the Python's Redis set() a difference kind of byte charset? I don't know.. Help me please.
Python Part
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 Part
@Autowired
private RedisTemplate<String, byte[]> redis;

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

Java 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


A: It's because Spring-Redis has a default valueSerializer, it will serialize the raw byte[]. 
byte[] rawValue(Object value) {

    if (valueSerializer() == null && value instanceof byte[]) {
        return (byte[]) value;
    }

    return valueSerializer().serialize(value);
}

So set Serializer to null solved this problem
@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;
}

