一、redis-py模块
安装:pip install redis -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
1.1 创建链接
import redis
redis_Db0 = redis.Redis( # 利用 redis 模块的 Redis() 类构建出 redis_Db0 对象
host="localhost", # 地址
port=6379, # 端口号
password="12345", # 密码(redis没有用户体系,访问只需要密码)
db=0 # 0逻辑库
)
1.2 创建连接池
import redis
redis_Pool = redis.ConnectionPool( # 利用 redis 模块的 ConnectionPool() 类构建出 redis_Pool 对象
host="localhost", # 地址
port=6379, # 端口号
password="12345", # 密码(redis没有用户体系,访问只需要密码)
db=0, # 0逻辑库
max_connections=10 # 最大连接数(因为是开发环境,所以写的少一些;如果是生产环境,必须要提高。)
)
1.3 创建与关闭连接
从连接池中获取的连接,不必关闭,垃圾回收的时候,连接会自动被归还到连接池
import redis
from redis_db import redis_Pool # 导入 redis_db模块 的 redis_Pool,自己建立的
"""
创建 redis 连接
"""
con = redis.Redis(
connection_pool=redis_Pool
)
"""
删除 redis 连接 (redis连接被删除后,会自动被 Python 的垃圾回收机制回收)
"""
del con
1.4 操作指令(一)
con.set('country','英国')
country = con.get('country').decode('utf-8')
操作指令(二) 字符串
con.delete('country', 'city') # 和redis中不同,redis-py用delete
con.mset({'country': '德国', 'city': '柏林'}) # 设置多个值时要用字典
result = con.mget('country','city') # 返回时元组类型
for item in result:
print(item.decode('utf-8'))
操作指令(三)列表
con.rpush('dame','董事会','秘书处','财务处') # 往列表内添加元素
con.lpop('dame') # 删除第一个元素
result = con.lrange('dame',0,-1) # 看列表中还有什么元素
for one in result:
print(one.decode('utf-8'))
操作指令(四)集合和有序集合
con.sadd('employee', 8001, 8002, 8003) # 集合中添加数据
con.srem('employee', 8001) # 移除集合中的数据8001
result = con.smembers('employee') # 获取集合所有数据
for one in result:
print(one.decode('utf-8'))
con.zadd('keyword', {'马云': 0, '张朝阳': 0, '丁磊': 0}) # 有序集合中添加数据,传输值为字典
con.zincrby('keyword', 10, '马云') # 有序集合分数值自增10
res = con.zrevrange('keyword', 0, -1) # 按照降序方式看结果
for one in res:
print(one.decode('utf-8'))
指令操作(五)哈希表
con.hmset('9999', {'name': 'scoot', 'sex': 'male', 'age': '35'}) # 哈希表增加多个元素
con.hset('9999', 'city', '纽约') # 增加哈希表元素
con.hdel('9999',"age") # 删除哈希表中元素
res = con.hexists('9999', 'name') # 判断哈希表中是否有某个元素
print(res)
result = con.hgetall('9999') # 获得哈希表中所有元素
for one in result:
print(one.decode('utf-8'),result[one].decode('utf-8'))
2.1 redis-py的事务函数
redis-py 模块用pipeline(管道)的方式向redis服务器传递批处理命令和执行事务
pipeline = con.pipeline() # 通过连接创建
pipeline.watch() # 监视记录
pipeline.multi() # 开始事务
pipeline.execute() # 提交事务
pipeline.reset() # 关闭pipeline,不关闭无法用连接池回收
pipline = con.pipeline() #
pipline.watch('9999') # 监测
pipline.multi() # 开启事务
pipline.hset('9999','name','jack') # 修改值
pipline.hset('9999','age',23)
pipline.execute() # 提交