Docker 配置 Redis
docker pull redis:6.2
docker run -d --name redis -p 6379:6379 --restart=always redis:6.2 redis-server --appendonly yes --requirepass "root"
docker ps -a
docker commit -a "aiden" -m "my Redis" redis redis:v1.0
docker stop redis
docker start redis
docker exec -it redis redis-cli -h localhost -p 6379 -a root
set root root
get root
select 10
操作 Redis
import redis, os
class RedisServer:
def __init__(self, host="localhost", port=6379, password="root", database=0):
"""
初始化, 创建连接池
:param host: IP, 默认本机
:param port: 端口, 默认 6379
:param password: 连接密码, 默认 root
:param database: 连接的数据库: 默认 0 (16 个)
"""
os.system("docker start redis")
self.pool = redis.ConnectionPool(host=host, port=port, password=password, db=database)
self.r = redis.Redis(connection_pool=self.pool)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.r.__del__()
self.pool.disconnect(inuse_connections=True)
os.system("docker stop redis")
def set(self, key, value, timeout=None):
"""
设置值, 不存在则创建, 存在则修改
:param key: 键
:param value: 值
:param timeout: 超时时间, 秒
:param px: 超时时间, 毫秒
:param nx: 为 True 时, 仅键不存在时创建
:param xx: 为 True 时, 仅键存在时创建
:param keepttl: 持续存储
"""
self.r.set(name=key, value=value, ex=timeout, px=None, nx=False, xx=False, keepttl=False)
def get(self, key):
"""
获取值
:param key: 键
"""
try:
return self.r.get(name=key).decode()
except Exception as e:
return None
def delete(self, *key):
"""
删除
:param key: 键, 一个 | 多个
:return: True(成功) | False(不存在)
"""
return True if self.r.delete(*key) else False
if __name__ == '__main__':
with RedisServer() as f:
val = f.get("root")
print(val)
val = f.get("1234")
print(val)
f.set("123", "456", timeout=10)
print(f.get("123"))
print(f.delete("123", "12"))
print(f.delete("12"))