1. 程式人生 > >python和redis之間的交互

python和redis之間的交互

set tin res exception 交互 chan exceptio 減少 input

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 redis

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

print(r.get(‘foo‘))

連接池:

import redis

pool = redis.ConnectionPool(host=‘localhost‘,port=6379,decode_responses=True)
# 默認設置的值和取得的值都是bytes類型,如果想改為str類型,可以添加decode_responses=True
r1 = 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,time

r = 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,time
import redis.exceptions
r = 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 redis

r = 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 redis
r = 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之間的交互