近期須要用到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)通過設置上述參數,攻克了編碼問題。
假設有人有更好的解釋和解決方式,求分享!