python和redis之間的互動

來源:互聯網
上載者:User

標籤:else   exe   get   red   except   watcher   port   scribe   inpu   

python和redis之間的互動一. redis模組

安裝模組:

pip3 install redis

串連方式:

r = redis.Redis(host=‘localhost‘,port=6379)

串連池:為了節約資源,減少多次串連帶來的消耗。

pool=redis.ConnectionPool(host=‘localhost‘,port=6379,decode_responses=True)

二.redis操作

常規操作:

import redisr = redis.Redis(host=‘localhost‘,port=6379)r.set(‘foo‘,‘bar‘)print(r.get(‘foo‘))

串連池:

import redispool = redis.ConnectionPool(host=‘localhost‘,port=6379,decode_responses=True)# 預設設定的值和取得的值都是bytes類型,如果想改為str類型,可以添加decode_responses=Truer1 = redis.Redis(connection_pool=pool)r2 = redis.Redis(connection_pool=pool)r1.set(‘name‘,‘jack‘)print(r1.get(‘name‘))r2.set(‘age‘,18)print(r2.get(‘age‘))print(r1.client_list())print(r2.client_list())

管道:

import redis,timer = redis.Redis(host=‘localhost‘,port=6379,decode_responses=True)pipe = r.pipeline(transaction=True)pipe.set(‘name1‘,‘Alin‘)pipe.set(‘name2‘,‘Lnda‘)pipe.set(‘name3‘,‘Tony‘)time.sleep(5) pipe.execute()print(r.mget(‘name1‘,‘name2‘,‘name3‘))

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

import redis,timeimport redis.exceptionsr = redis.Redis(host=‘localhost‘,port=6379,decode_responses=True)pipe = r.pipeline()print(r.get(‘name1‘))try:    pipe.multi()    pipe.set(‘age1‘,22)    pipe.set(‘age2‘,23)    pipe.set(‘age3‘,24)    time.sleep(5)    pipe.execute()    print(r.mget(‘age1‘,‘age2‘,‘age3‘))except redis.exceptions.WatchError as e:    print(‘Error‘)

訂閱和發布:
發布方:

import redisr = redis.Redis(host=‘localhost‘,port=6379,decode_responses=True)while True:    msg = input(‘echo>>:‘)    if len(msg) == 0:        continue    elif msg == ‘quit‘:        r.publish(‘cctv1‘,msg)        break    else:        r.publish(‘cctv1‘,msg)

訂閱者:

import redisr = redis.Redis(host=‘localhost‘,port=6379,decode_responses=True)chan = r.pubsub() #返回一個發布訂閱對象msg_reciver = chan.subscribe(‘cctv1‘) #訂閱msg = chan.parse_response()  # 返回一個確認print(msg)print(‘訂閱成功,開始接收...‘)while True:    msg = chan.parse_response()  #接收訊息    if msg[2] == ‘quit‘:  #格式:類型,頻道,訊息        break    else:        print(‘>>:‘, msg[2])

python和redis之間的互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.