1. 程式人生 > 資料庫 >python實現與redis互動操作詳解

python實現與redis互動操作詳解

本文例項講述了python實現與redis互動操作。分享給大家供大家參考,具體如下:

相關內容:

  • redis模組的使用
    • 安裝模組
    • 匯入模組
    • 連線方式
    • 連線池
    • 操作
      • 設定值
      • 獲取值
  • 管道
  • 事務
  • 訂閱\釋出

首發時間:2018-03-14 15:02


python可以使用redis模組來跟redis互動


redis模組的使用:

  • 安裝模組: pip3 install redis
  • 匯入模組:import redis
  • 連線方式:
    • 嚴格連線模式:r=redis.StrictRedis(host="",port=)
    • 更Python化的連線模式:r=redis.Redis(host="",port=)
    • StrictRedis用於實現大部分官方的命令,並使用官方的語法和命令
    • Redis與StrictRedis的區別是:Redis是StrictRedis的子類,用於向前相容舊版本的redis-py,並且這個連線方式是更加"python化"的
  • 連線池:
    • 為了節省資源,減少多次連線損耗,連線池的作用相當於總攬多個客戶端與服務端的連線,當新客戶端需要連線時,只需要到連線池獲取一個連線即可,實際上只是一個連線共享給多個客戶端。
      import redis
      
      pool= redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)
      
      r=redis.Redis(connection_pool=pool)
      r2=redis.Redis(connection_pool=pool)
      r.set('apple','a')
      print(r.get('apple'))
      r2.set('banana','b')
      print(r.get('banana'))
      
      print(r.client_list())
      print(r2.client_list())#可以看出兩個連線的id是一致的,說明是一個客戶端連線
  • 操作:
    • 值的設定和獲取,可以參考redis的命令,redis模組中的對應功能的函式名基本與redis中的一致
    • 【注意預設情況下,設定的值或取得的值都為bytes型別,如果想改為str型別,需要在連線時新增上decode_responses=True】
    • 設定值:
      • redis中set() ==>r.set()
      • redis中setnx() ==>r.set()
      • redis中setex() ==>r.setex()
      • redis中setbit() ==>r.setbit()
      • redis中mset() == > r.mset()
      • redis中hset() ==>r.hset()
      • redis中sadd() == >r.sadd()
      • 其他。。。基本redis的命令名與redis模組中的函式名一致
    • 獲取:
      • redis中get() ==》r.get()
      • redis中mget() ==》r.mget()
      • redis中getset() ==》r.getset()
      • redis中getrange() ==》r.getrange()
      • 其他。。。基本redis的命令名與redis模組中的函式名一致

如果想要了解更多redis命令,可以參考我的另外一篇博文:

一文學redis操作(記錄向)<點選即可跳轉>

import redis
r=redis.Redis(host='localhost',decode_responses=True)
# r=redis.StrictRedis(host='localhost',port=6379)

r.set('key','value')
value=r.get('key')
# print(type(value))
print(value)
r.hset('info','name','lilei')
r.hset('info','age','18')
print(r.hgetall('info'))
r.sadd('course','math','english','chinese')
print(r.smembers('course'))

管道:

一般情況下,執行一條命令後必須等待結果才能輸入下一次命令,管道用於在一次請求中執行多個命令。

  • 引數介紹:
    • transaction:指示是否所有的命令應該以原子方式執行。
import redis,time

r=redis.Redis(host="localhost",decode_responses=True)

pipe=r.pipeline(transaction=True)

pipe.set('p1','v2')
pipe.set('p2','v3')
pipe.set('p3','v4')
time.sleep(5)
pipe.execute()

事務:

python中可以使用管道來代替事務:

  • 補充:監視watch:pipe.watch()
import redis,time
import redis.exceptions
r=redis.Redis(host='localhost',decode_responses=True)
pipe=r.pipeline()
print(r.get('a'))


try:
  # pipe.watch('a')
  pipe.multi()
  pipe.set('here','there')
  pipe.set('here1','there1')
  pipe.set('here2','there2')
  time.sleep(5)
  pipe.execute()

except redis.exceptions.WatchError as e:
  print("Error")

訂閱\釋出:

    • 釋出方:
import redis
r=redis.Redis(host="localhost",decode_responses=True)

#釋出使用publish(self,channel,message):Publish ``message`` on ``channel``.
Flag=True
while Flag:
  msg=input("主播請講話>>:")
  if len(msg)==0:
    continue
  elif msg=='quit':
    break
  else:
    r.publish('cctv0',msg)
    • 訂閱方:
      • 當訂閱成功後,第一次接收返回的第一個訊息是一個訂閱確認訊息:image
import redis
r=redis.Redis(host="localhost",message):Publish ``message`` on ``channel``.
Flag=True
chan=r.pubsub()#返回一個釋出/訂閱物件
msg_reciver=chan.subscribe('cctv0')#訂閱

msg=chan.parse_response()#第一次會返回訂閱確認資訊
print(msg)
print("訂閱成功,開始接收------")
while Flag:
  msg=chan.parse_response()#接收訊息
  print(">>:",msg[2])#此處的資訊格式['訊息型別','頻道','訊息'],所以使用[2]來獲取

更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python編碼操作技巧總結》、《Python資料結構與演算法教程》、《Python Socket程式設計技巧總結》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》

希望本文所述對大家Python程式設計有所幫助。