当前位置 : 主页 > 编程语言 > python >

Python3操作Redis

来源:互联网 收集:自由互联 发布时间:2022-06-15
一、Python3操作Redis 安装所需的库: redis库(操作Redis单点和Redis哨兵集群):pip3 install redis redis-py-cluster(操作Redis cluster集群):pip3 install redis-py-cluster 一)Python3操作Redis单实例 import

一、Python3操作Redis

  安装所需的库:

  redis库(操作Redis单点和Redis哨兵集群):pip3 install redis 

  redis-py-cluster(操作Redis cluster集群):pip3 install redis-py-cluster

  一)Python3操作Redis单实例

import redis

res_conn = redis.StrictRedis(host='192.30.96.33', port='6379', db=0, password='123456')
res_conn.set('test', '123')
res_conn.get('test')

  二)Python3操作sentinel集群

from redis.sentinel import Sentinel
sentinel = Sentinel(
[
('192.30.96.33', 26380),
('192.30.96.33', 26381),
('192.30.96.33', 26382)
],
socket_timeout=0.1
)
sentinel.discover_master('mymaster')
sentinel.discover_slaves('mymaster')

# 配置读写分离
# 写节点
master = sentinel.master_for('mymaster', socket_timeout=0.1)
# 读节点
slave = sentinel.slave_for('mymaster', socket_timeout=0.1)

# 读写分离测试 key
master.get('devops', 'ok')
slave.get('devops')

  三)Python3操作Redis cluster集群

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "wzs"
#2022/2/3

from rediscluster import RedisCluster

class RedisClusterOps(object):
def __init__(self,conn_list):
self.conn_list = conn_list

def connect(self):
'''
连接redis集群
:return: object
'''
try:
# 连接无密码redis集群
redisconn = RedisCluster(startup_nodes=self.conn_list)
# 连接有密码redis集群
# redisconn = RedisCluster(startup_nodes=self.conn_list, password='123456')
return redisconn
except Exception as e:
print(e)
print("错误,连接redis集群失败")
return False
def get_state(self):
"""
获取状态
:return:
"""
res = RedisClusterOps(self.conn_list).connect()
if not res:
return False

info_dic = res.cluster_info() # 查看info信息, 返回dict

for i in info_dic: # 遍历dict
ip = i.split(":")[0]
if info_dic[i].get('cluster_state'): # 获取状态
print("节点状态, ip: ", ip, "value: ", info_dic[i].get('cluster_state'))

def get_has_aof(self):
'''
查看aof是否打开
:return:
'''
res = RedisClusterOps(self.conn_list).connect()
if not res:
return False
dic = res.config_get('appendonly') # 从config配置项中查询appendonly
for i in dic:
ip = i.split(":")[0]
# print(dic[i])
if dic[i].get('appendonly'):
print("aof开关,ip:", ip, "; value:", dic[i].get('appendonly'))
redis_base_conn = [
{'host': '192.30.96.33', 'port': '7001'},
{'host': '192.30.96.33', 'port': '7002'},
{'host': '192.30.96.36', 'port': '7001'},
{'host': '192.30.96.36', 'port': '7002'},
{'host': '192.30.96.37', 'port': '7001'},
{'host': '192.30.96.37', 'port': '7002'}
]

res = RedisClusterOps(redis_base_conn).connect()
# if not res:
# print("连接redis集群失败")
# else:
# print("连接redis集群成功")

## 获取集群各节点状态
# RedisClusterOps(redis_base_conn).get_state()

## 查看aof是否打开
# RedisClusterOps(redis_base_conn).get_has_aof()


## Redis 集群设置key,获取key
res.set('opsadmin','ok')
print("name is:", res.get('opsadmin'))
print("name is:", res.delete('opsadmin'))
print("name is:", res.get('opsadmin'))





上一篇:Python 增删改查
下一篇:没有了
网友评论