一、一般連接redis情況
1 from redis import Redis 2 # 實例化redis對象 3 rdb = Redis(host='localhost', port=6379, db=0) 4 rdb.set('name', 'root')
5 name = rdb.get('name')
6 print(name)
這種情況連接數據庫,對數據的存取都是字節類型,存取時還得轉碼一下,一般不推薦這種方法
二、連接池連接redis
1 from redis import ConnectionPool, Redis 2 pool = ConnectionPool(host='localhost', port=6379, db=0) 3 rdb = Redis(connection_pool=pool) 4 rdb.get('name')
這種連接池連接redis時也會有上述情況出現,所以一般也不推薦
三、redis連接的推薦方式
為了避免上述情況,redis在實例化的時候給了一個參數叫decode_response,默認值是False,如果我們把這個值改為True,則避免了轉碼流程,直接對原數據進行操作
1 from redis import ConnectionPool, Redis 2 pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True) 3 rdb = Redis(connection_pool=pool)
4 rdb.set('name2', 'rooter') 5 name2 = rdb.get('name2')
6 print(name2)