Python redis
跳到导航
跳到搜索
Connect
集群
# pip3 install redis-py-cluster import rediscluster rnode = [ {"host": "192.168.0.229", "port": 6379}, {"host": "192.168.0.229", "port": 6380}, {"host": "192.168.0.148", "port": 6379}, {"host": "192.168.0.148", "port": 6380}, {"host": "192.168.0.249", "port": 6379}, {"host": "192.168.0.249", "port": 6380} ] # decode_responses=True,返回值字符串(否则为 byte) rc = rediscluster.RedisCluster(startup_nodes=rnode, decode_responses=True)
单机
Redis 的单机使用在集群上时,如果读的数据不在连接主机上,会出现错误。
# pip3 install redis import redis rc = redis.Redis(host='192.168.0.229', port=6379, db=0)
操作
Connection Pool
使用连接池来管理所有连接,避免每次建立、释放连接的开销。
# redis rcp = redis.ConnectionPool(host='192.168.0.229', port=6379, db=0) rc = redis.Redis(connection_pool = rcp, decode_responses=True) rc2 = redis.Redis(connection_pool = rcp, decode_responses=True) # redis cluster rcp = rediscluster.ClusterConnectionPool(startup_nodes=rnode, decode_responses=True) rc = rediscluster.RedisCluster(connection_pool=rcp)
管道
Redis 管道技术可以在服务端未响应时,客户端可以继续向服务端发送请求,并最终一次性读取所有服务端的响应。批量写入时,使用pipeline可以大幅度提升性能
# 使用 rp 代替 rc rp = rc.pipeline(transaction = False) # 足够数量的 rp.set 后,提交 FLAG = rp.execute()
set
rc.set('test', 'Hello, World!') rc.set('test1', 'Hello, Redis!') rc.set('test2', 'Hello, RDS!')
get
rc.get('test')
keys
rc.keys('*test*') rc.keys('*test?')
scan
rc.scan(0, '*0123*', 10) {'192.168.0.229:6379': (6292935, ['86.56789.410/154710123', '86.56789.410/117012344']), '192.168.0.148:6379': (2099409, ['86.56789.410/121501232', '86.56789.410/110123399']), '192.168.0.249:6379': (6293256, ['86.56789.410/129012348', '86.56789.410/199530123'])}
delete
rc.delete('test2')
各节点记录数
rc.dbsize()
有效时间
100 secs
# rc.set('test', 'Hello, World!', 100) rc.set('test', 'Hello, World!') rc.expire('test', 100) rc.get('test')