Redis 中文入库成功,读取数据写入文件乱码问题

时间:2022-06-02 08:30:22

近期须要用到redis ,可是在编码这个问题上,纠结了非常久。

       需求 :每天一个进程将中文文件入库到redis中(不定时更新) ,另外几个进程读取redis中的信息 ,并处理数据结果。使用的redis模块 :入库正常,读取数据成功,以GBK编码写入文件出现异常。  通过下面參数连接 redis :

       client  = redis.StrictRedis(host='localhost', port=6379, db=0, password="***") 从*上了解到 :最好传入一个str类型的value给redis,而不是unicode,否则,redis会直接使用set命令,将你的value设置为utf-8的格式,当你使用get方法获取数据的时候,redis本身并不关心你value的数据的类型,而给你返回一个str类型的value。因此,你存储的时候value的类型是关键所在
,主要体如今redis-py的源代码中 :

        """
Encode the value so that it's identical to what we'll
read off the connection
"""
if self.decode_responses and isinstance(value, bytes):
value = value.decode(self.encoding, self.encoding_errors)
elif not self.decode_responses and isinstance(value, unicode):
value = value.encode(self.encoding, self.encoding_errors)
return value

解决方法 :在使用redis API 连接数据库时 :

class  redis.StrictRedis(host='localhost', port=6379, db=0, password=None, socket_timeout=None,connection_pool=None, charset='GBK', errors='strict',
decode_responses=True, unix_socket_path=None)

通过设置上述參数,攻克了编码问题。

假设有人有更好的解释和解决方式,求分享!