推荐清华源
pip install redis -i
import redis
r = redis.redis(
host:"localhost",
port:6379,
password="",
db=0
)
import redis
pool = redis.ConnectionPool(
redis.redis(
host:"localhost",
port:6379,
password="",
db=0,
max_connections=20)
从连接池中获取的连接,不必关闭,垃圾回收的时候,连接会自动被归还到连接池
r = redis.Redis(
connection_pool=pool,
)
...
del r
# redis_db.py
import redis
pool = redis.ConnectionPool(
host="localhost",
port=6379,
password="",
db=0,
max_connection=20)
# demo_redis.py
from redis_db import pool
import redis
con = redis.Redis(
connection_pool=pool
)
del con
con.set("country", "England")
con.set("city", "London")
city = con.get("city").decode("utf-8")
print(city)
r.delete("country", "city")
r.mset({"country":"Japan", "city":"tokin"})
result = r.mget("counry", "city")
for one in result:
print(one.decode("utf-8"))
try-catch版:
import redistry:
try:
pool = redis.ConnectionPool(
host="localhost",
port=6379,
password="",
db=0,
max_connection=20
)
except Exception as e:
print(e)
# demo2.py
from redis_db import pool
import redis
con = redis.Redis(
connection_pool=pool
)
try:
con.delete("country", "city")
con.mset("country": "德国", "city": "柏林")
result = con.mget("country", "city")
for one in result:
print(one.decode("utf-8"))
except Exception as e:
print(e)
finally
del con
# demo3.py
from redis_db import pool
import redis
con = redis.Redis(connection_pool=pool)
try:
con.rpush("dname", "董事会", "秘书处", "财务部", "技术部")
con.lpop("dname")
result = con.lrange("dname", 0, -1)
for one in result:
print(one.decode("utf-8"))
except Exception as e:
print(e)
finally:
del con
# demo4.py
con.sadd("empolyee", 9001, 9002, 9003)
con.srem("employee", 9001)
result = con.smembers("employee")
con.zadd("keyword", {"马云": 0, ""})
con.zadd("keyword", {"马云": 0, "张朝阳":0, "丁磊": 0})
con.zincrby("keyword", "10", "马云")
result = con.revrange("keyword", 0, -1)
# demo5.py
from redis_db import pool
import redis
con = redis.Redis(
connection_pool=pool
)
try:
con.hmset("9527", {"name":"Scott", "sex":"male"})
con.hset("9527", "city", "纽约")
con.hdel("9527", "age")
result = con.hexists("9527", "name")
print(result)
result = con.hgetall("9527")
for one in result:
print(one.decode("utf-8"), result[one].decode("utf-8"))
except Exception as e:
print(e)
finally:
del con
redis-py模块用pipline(管道)的方式向Redis服务器传递批处理处理命令和执行事务
pipline = con.pipline() # 创建pipline对象
pipline.watch(...) # 监视记录
pipline.multi() # 开启事务
pipline.excute() # pipline来增删改查,对事务进行提交
pipline.reset() # 一定要关闭pipline,不然连接池没法回收
# demo6.py
from redis_db import pool
import redis
con = redis.Redis(
conection_pool=pool
)
try:
pipline = con.pipline()
pipline.watch("9527")
pipline.multi()
pipline.hset("9527", "name", "Jackylove")
pipline.hset("9527", "age", 23)
pipline.execute
except Exceptyion as e:
print(e)
finally:
if "pipline" in dir():
pipline.reset()
del con