一、安装
1、单机和哨兵,使用的是redis模块,所以下载redis即可,使用pip或者pip3命令来安装。
pip3 install redis
2、集群需要用到rediscluster模块,采用以下命令安装redis-py-cluster即可,最好指定版本
pip3 install redis-py-cluster=1.3.6
二、连接和使用
1、redis单机连接
import redis
conn = redis.StrictRedis(connection_pool=redis.ConnectionPool(
host="192.168.233.1", port="6379", password=""
))
# string类型的写入读取
conn.set("key_name", "value")
conn.get("key_name")
# 列表类型的读取写入
conn.lpush("key_name", "value1", "value2",...)
conn.lrange("key_name", 0, -1) # 列出key_name下的所有值
2、redis哨兵连接
from redis.sentinel import Sentinel
sentinel_list = [
("192.168.233.1", "26379"),
("192.168.233.2", "26379"),
("192.168.233.3", "26379")
]
mySentinel = Sentinel(sentinel_list)
master = mySentinel.master_for("mymaster", db=0)
slave = mySentinel.slave_for("mymaster", db=0)
# 使用master进行写的操作,使用slave进行读的操作
master.hset("key_name", "filed", "value")
slave.hget("key_name", "filed")
slave.hgetall("key_name")
3、redis集群连接
from rediscluster import StrictRedisCluster
cluster_nodes = [{"host": "192.168.233.1", "port": "9001"},
{"host": "192.168.233.1", "port": "9002"},
{"host": "192.168.233.1", "port": "9003"},
{"host": "192.168.233.2", "port": "9004"},
{"host": "192.168.233.2", "port": "9005"},
{"host": "192.168.233.2", "port": "9006"}]
password = "root"
conn = StrictRedisCluster(
startup_nodes=cluster_nodes,
decode_response=True,
password=password,
max_connection=300
)
# 写入值,获取值
conn.set("key_name", "value")
conn.get("key_name")
三、Django使用redis
1、setting文件内进行连接配置
直连redis的配置
# redis配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100}
# "PASSWORD": "123",
}
}
}
使用sentinel的配置
# settings.py
# django-sentinel==0.1.0
LOCATION = "mymaster/192.168.1.1:26379,192.168.1.2:26379,192.168.1.3:26379/1"
REDIS_PASSWORD = "mypassword"
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": LOCATION,
"OPTIONS": {
"PASSWORD": REDIS_PASSWORD,
"CLIENT_CLASS": "django_sentinel.SentinelClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100}
}
}
}
2、导入模块,视图函数使用
from django_redis import get_redis_connection
conn = get_redis_connection('default')
print(conn.hgetall('xxx'))
四、redis的操作
redis有五种数据类型:string, set, list, hash, sorted set
常用的操作有:增加,查询,删除
以下是python中,使用redis连接后的操作,其中conn即为上边的单机、集群、哨兵的连接:
1、string字符串
# 增加\查询\删除
conn.set(key, value)
conn.get(key)
conn.delete(key)
2、set集合
# 增加\查询\删除
conn.sadd(key, value1, value2...)
conn.smembers(key)
conn.delete(key)
3、list列表
# 增加\查询\删除
conn.lpush(key, value1, value2,...)
conn.lrange(key, start, end) # 比如列出所有conn.lrange("key_name", 0, -1)
conn.delete(key)
4、hash哈希
# 增加\查询\删除
conn.hset(key, field, value)
conn.hget(key, filed)
conn.hgetall(key)
conn.delete(key)
5、sorted set有序集合
# 增加\查询\删除
# 注意:有序集合键值对是与redis中操作相反的,redis中:zadd key score value
# python中,分值对应的是字典中的值
conn.zadd(key, {value1: score1, value2: score2})
conn.zrange(key, start, end)
conn.delete(key)