Python?redis模塊的使用教程指南
1.安裝模塊
Python 要使用 redis,需要先安裝 redis 模塊:
pip install redis
測試安裝:
redis 取出的結(jié)果默認(rèn)是字節(jié),我們可以設(shè)定 decode_responses=True 改成字符串
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set('name', 'dahezhiquan') # 設(shè)置 name 對應(yīng)的值
print(r['name']) # dahezhiquan
print(r.get('name')) # dahezhiquan
print(type(r.get('name'))) # <class 'str'>
2.連接池
redis-py 使用 connection pool 來管理對一個 redis server 的所有連接,避免每次建立、釋放連接的開銷。
默認(rèn),每個Redis實例都會維護(hù)一個自己的連接池。可以直接建立一個連接池,然后作為參數(shù) Redis,這樣就可以實現(xiàn)多個 Redis 實例共享一個連接池。
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set('name', 'dahe')
print(r.get('name')) # dahe
3.redis 基本命令 String
set,在 Redis 中設(shè)置值,默認(rèn),不存在則創(chuàng)建,存在則修改:
語法:
set(name, value, ex=None, px=None, nx=False, xx=False)
參數(shù):
- ex - 過期時間(秒)
- px - 過期時間(毫秒)
- nx - 如果設(shè)置為True,則只有name不存在時,當(dāng)前set操作才執(zhí)行
- xx - 如果設(shè)置為True,則只有name存在時,當(dāng)前set操作才執(zhí)行
案例1:(3秒后,name的值就會變?yōu)镹one)
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set('name', 'xiaoqian', ex=3) # 設(shè)置過期時間為3秒
print(r.get('name')) # xiaoqian
三秒后再次獲取name的值:
print(r.get('name')) # None
mset,批量獲取值:
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set("name1", "xiaoqian")
r.set("name2", "xiaoguo")
print(r.mget('name1', 'name2')) # ['xiaoqian', 'xiaoguo']
getset(name, value),設(shè)置新值并獲取原來的值:
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
print(r.getset("name1", "heihei")) # xiaoqian
print(r.get("name1")) # heihei
strlen(name),返回name對應(yīng)值的字節(jié)長度(一個漢字3個字節(jié)):
print(r.strlen("name"))
incr(name, amount=1),自增 name 對應(yīng)的值,當(dāng) name 不存在時,則創(chuàng)建 name=amount,否則,則自增:
參數(shù):
- name - Redis的name
- amount - 自增數(shù)(必須是整數(shù))
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set("like", 521)
r.incr("like", amount=1)
print(r.get("like")) # 522
可以使用incrbyfloat方法自增浮點數(shù)類型
使用decr進(jìn)行自減操作
append(key, value),在redis name對應(yīng)的值后面追加內(nèi)容:
參數(shù):
- key - redis的name
- value - 要追加的字符串
r.append("name1", "world")
print(r.get("name1"))
4.redis 基本命令 hash
hset(name, key, value),單個增加–修改:
name對應(yīng)的hash中設(shè)置一個鍵值對(不存在,則創(chuàng)建;否則,修改)
參數(shù):
- name - redis的name
- key - name對應(yīng)的hash中的key
- value - name對應(yīng)的hash中的value
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.hset("dahe", "name", "guo")
r.hset("dahe", "age", 28)
# 獲取dahe的所有key
print(r.hkeys("dahe")) # ['name', 'age']
print(r.hget("dahe", "name")) # guo
print(r.hmget("dahe", "name", "age")) # ['guo', '28']
hmset(name, mapping),在name對應(yīng)的hash中批量設(shè)置鍵值對:
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.hmset("hash1", {"k1": "v1", "k2": "v2", "k3": "v3"})
print(r.hmget("hash1", "k1", "k2", "k3")) # ['v1', 'v2', 'v3']
hgetall(name),取出所有的鍵值對:
print(r.hgetall("dahe")) # {'name': 'guo', 'age': '28'}
hvals(name),得到所有的value:
print(r.hvals("dahe")) # ['guo', '28']
hdel(name,*keys),將name對應(yīng)的hash中指定key的鍵值對刪除:
r.hdel("hash1", "k1")
print(r.hgetall("hash1")) # {'k2': 'v2', 'k3': 'v3'}
hincrby(name, key, amount=1),自增自減整數(shù):
參數(shù):
name - redis中的name
key - hash對應(yīng)的key
amount - 自增數(shù)(整數(shù),負(fù)數(shù)表示自減)
hincrbyfloat(name, key, amount=1.0)表示自增自減浮點數(shù)
5.redis基本命令 list
lpush(name,values),增加:
在name對應(yīng)的list中添加元素,每個新的元素都添加到列表的最左邊
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.lpush("score", 10, 20, 30, 40)
print(r.lrange("score", 0, -1)) # ['40', '30', '20', '10']
rpush表示從右邊增加
r.lset(name, index, value),對name對應(yīng)的list中的某一個索引位置重新賦值:
參數(shù):
- name - redis的name
- index - list的索引位置
- value - 要設(shè)置的值
redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.lset("score", 0, 521)
print(r.lrange("score", 0, 4)) # ['521', '30', '20', '10', '40']
r.lrem(name, value, num),刪除:
參數(shù):
name - redis的name
value - 要刪除的值
num - num=0,刪除列表中所有的指定值;
- num=2 - 從前到后,刪除2個, num=1,從前到后,刪除左邊第1個
- num=-2 - 從后向前,刪除2個
r.lrem("list2", "11", 1) # 將列表中左邊第一次出現(xiàn)的"11"刪除
print(r.lrange("list2", 0, -1))
r.lrem("list2", "99", -1) # 將列表中右邊第一次出現(xiàn)的"99"刪除
print(r.lrange("list2", 0, -1))
r.lrem("list2", "22", 0) # 將列表中所有的"22"刪除
print(r.lrange("list2", 0, -1))
lindex(name, index),取值:
print(r.lindex("list2", 0)) # 取出索引號是0的值
自定義增量迭代:
由于redis類庫中沒有提供對列表元素的增量迭代,如果想要循環(huán)name對應(yīng)的列表的所有元素,那么就需要獲取name對應(yīng)的所有列表。
但是,如果列表非常大,那么就有可能在第一步時就將程序的內(nèi)容撐爆,所有有必要自定義一個增量迭代的功能:
def list_iter(name):
"""
自定義redis列表增量迭代
:param name: redis中的name,即:迭代name對應(yīng)的列表
:return: yield 返回 列表元素
"""
list_count = r.llen(name)
for index in range(list_count):
yield r.lindex(name, index)
# 使用
for item in list_iter('list2'): # 遍歷這個列表
print(item)
6.redis基本命令 set
sadd(name,values),新增:
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.sadd("set1", 33, 44, 55, 66) # 往集合中添加元素
print(r.scard("set1")) # 4(集合長度)
print(r.smembers("set1")) # {'66', '44', '55', '33'}(取出集合所有元素)
srem(name, values),在name對應(yīng)的集合中刪除某些值:
r.srem("set1", 66)
print(r.smembers("set1")) # {'44', '33', '55'}
python-redis set支持集合的所有操作,請參考官方文檔
7.其他常用操作
delete(*names),刪除:
根據(jù)刪除redis中的任意數(shù)據(jù)類型(string、hash、list、set、有序set)
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.delete("set2")
expire(name ,time),為某個redis的某個name設(shè)置超時時間:
r.expire("set1", time=3)
rename(src, dst),重命名:
r.rename("dahe", "dahe-1")
8.管道
redis默認(rèn)在執(zhí)行每次請求都會創(chuàng)建(連接池申請連接)和斷開(歸還連接池)一次連接操作,如果想要在一次請求中指定多個命令,則可以使用pipline實現(xiàn)一次請求指定多個命令,并且默認(rèn)情況下一次pipline是原子性操作
實例:
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
pipe = r.pipeline() # 創(chuàng)建一個管道
pipe.set('name', 'jack')
pipe.set('role', 'sb')
pipe.sadd('age', '18')
pipe.execute()以上就是Python redis模塊的使用教程指南的詳細(xì)內(nèi)容,更多關(guān)于Python redis模塊的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于python tushare Tkinter構(gòu)建的簡單股票可視化查詢系統(tǒng)(Beta v0.13)
這篇文章主要介紹了python tushare Tkinter構(gòu)建的簡單股票可視化查詢系統(tǒng)(Beta v0.13),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
Python編寫可視化界面的詳細(xì)教程(Python+PyCharm+PyQt)
最近開始學(xué)習(xí)Python,但只限于看理論,編幾行代碼,覺得沒有意思,就想能不能用Python編寫可視化的界面,遂查找了相關(guān)資料,發(fā)現(xiàn)了PyQt,所以本文介紹了Python+PyCharm+PyQt編寫可視化界面的詳細(xì)教程,需要的朋友可以參考下2024-07-07
Python代碼集pathlib應(yīng)用之獲取指定目錄下的所有文件
這篇文章主要介紹了Python代碼集pathlib應(yīng)用之獲取指定目錄下的所有文件,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03

