一,redis簡介
- Redis是一個(gè)開源的使用ANSIC語言編寫、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫,并提供多種語言的API。是一個(gè)非關(guān)系型數(shù)據(jù)庫,經(jīng)常會(huì)用作緩存,消息中間件的操作
二,redis優(yōu)勢
- 速度快,因?yàn)閿?shù)據(jù)存在內(nèi)存中
- 支持豐富數(shù)據(jù)類型,支持字符串,哈希表,列表,集合,有序集合
- 支持事務(wù),操作都是原子性
- 豐富的特性:可用于緩存,消息,按key設(shè)置過期時(shí)間,過期后將會(huì)自動(dòng)刪除
三,redis安裝
windows直接打開解壓下載好的文件夾,然后在此文件夾下打開終端
- 啟動(dòng)redis服務(wù)器
redis-server redis.windows.conf
-redis使用
redis-cli.exe
ubuntu下直接終端下輸入sudo apt-get install redis-server即可,不過版本較低,要選擇的可以去官網(wǎng)源碼下載安裝
四,python連接redis
1.直接連接
#導(dǎo)入redis模塊
import redis
#連接數(shù)據(jù)庫,創(chuàng)建redis實(shí)例化對(duì)象
r = redis.Redis(password="123456", decode_responses=True)
#向數(shù)據(jù)庫中添加字符串?dāng)?shù)據(jù)
r.set("愛你","有多愛")
#查看數(shù)據(jù)
print(r.get("愛你"))
2.使用連接池來進(jìn)行連接
import redis
#創(chuàng)建連接池
pool = redis.ConnectionPool(password="123456", decode_responses=True)
#使用連接池對(duì)象去鏈接redis
r = redis.Redis(connection_pool=pool)
#查看數(shù)據(jù)
print(r.get("xxx"))
3.PipeLine模式
import redis
r = redis.Redis(password="123456", decode_responses=True)
#創(chuàng)建一個(gè)管道對(duì)象
pipe = r.pipeline()
try:
#鏈?zhǔn)讲僮? pipe.set("name", "狗蛋").set("age",18).set("sex",1)
except Exception as e:
print(e)
#把管道清空
pipe.reset()
else:
#執(zhí)行操作
pipe.execute()