解决方案:在连接Redis时指定UTF-8编码。使用Python时,代码如下:
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
# 读取数据
value = r.get('key')
print(value) # 现在不会乱码了
来源1
Redis客户端连接时设置编码格式为UTF-8,就能解决读取中文乱码问题。在Jedis中:Jedis jedis = new Jedis("localhost", 6379); jedis.set("key", "中文"); String value = jedis.get("key"); System.out.println(value);
来源2
使用Spring Data Redis时,在配置中添加:@Bean public RedisTemplate
来源3
如果是redis-cli命令行,启动时用:redis-cli --raw 或者在.conf文件中设置:tcp-keepalive 0,然后重启Redis服务。读取时直接echo "get key" | redis-cli -r 1 --raw。
来源4
Python redis-py库,关键是decode_responses=True参数,它会自动将bytes解码为str,使用UTF-8。pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True) r = redis.Redis(connection_pool=pool)
来源5
Node.js的ioredis:const Redis = require('ioredis'); const redis = new Redis({ lazyConnect: true }); // 默认UTF-8,但确认string类型。redis.set('key', '中文测试'); redis.get('key').then(console.log);
来源6
检查Redis服务器的编码:CONFIG GET * | grep encoding,通常是UTF-8。如果存入时用了其他编码,删除key重新用UTF-8存入。
FAQ
Q: 为什么Redis存中文正常,读出来乱码?
A: 因为客户端读取时没指定decode为UTF-8,默认bytes显示乱码,加decode_responses=True。
Q: Java项目怎么快速修复?
A: 用StringRedisSerializer序列化key和value。
Q: redis-cli怎么处理?
A: 用--raw参数或管道命令。
Q: 历史数据乱码怎么办?
A: 删除key,用正确编码重新写入。