zoukankan      html  css  js  c++  java
  • Redis 中文入库成功,读取数据写入文件乱码问题

    近期须要用到redis ,可是在编码这个问题上,纠结了非常久。
           需求 :每天一个进程将中文文件入库到redis中(不定时更新) ,另外几个进程读取redis中的信息 ,并处理数据结果。使用的redis模块 :入库正常,读取数据成功,以GBK编码写入文件出现异常。  通过下面參数连接 redis :
           client  = redis.StrictRedis(host='localhost', port=6379, db=0, password="***") 从stackoverflow上了解到 :最好传入一个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)

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


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



  • 相关阅读:
    几个关于文本文件、字符串、编码的函数
    海量数据解决思路之Hash算法
    从头到尾彻底解析哈希表算法
    几个 GetHashCode 函数
    DELPHI指针的使用
    关于Delphi中的字符串的详细分析
    TStringList常用操作
    Pascal 排序算法
    Delphi THashedStringList用法
    Delphi代码创建形式规范 1.0
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4332178.html
Copyright © 2011-2022 走看看