在Java中,要连接RedisCluster就得使用JedisCluster或者Lettuce,那么Python中有没有类型的框架呢?答案肯定是有了,这就是redis-py-cluster了,下面就简单的介绍下redis-py-cluster的使用案例了。

版本支持

Python版本支持:

  • 2.7
  • 3.3
  • 3.4.1+
  • 3.5
  • 3.6
  • 3.7

Python redis版本支持:

redis >= 2.10.2, <= 2.10.5

Redis Cluster版本支持:

只需要大于redis3.0的集群即可

安装依赖包

使用pip安装redis-py-cluster

1
pip3 install redis-py-cluster

对于内网环境的用户来说可以下载redis-py-cluster的源码,使用如下命令安装:

1
python3 setup.py install

使用手册

初始化链接

1
2
3
4
5
6
from rediscluster import StrictRedisCluster

startup_nodes = [{"host": "10.10.170.161", "port": "7000"}, {"host": "10.10.170.161", "port": "7001"},
{"host": "10.10.170.161", "port": "7002"}, {"host": "10.10.170.161", "port": "7003"},
{"host": "10.10.170.161", "port": "7004"}, {"host": "10.10.170.161", "port": "7005"}]
redis_cluster = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)

关于StrictRedisCluster的构造函数,还有如下参数:

  • host
  • port
  • max_connections
  • max_connections_per_node
  • init_slot_cache
  • readonly_mode
  • reinitialize_steps
  • skip_full_coverage_check
  • nodemanager_follow_cluster
  • connection_class
  • **kwargs
    • db
    • password
    • socket_timeout
    • encoding
    • encoding_errors
    • decode_responses
    • retry_on_timeout
    • max_connections
    • connection_pool

以上参数看字面意思就知道啥意思就不过多说了,但是请注意db这个参数是不支持的,因为Redis Cluster仅支持一个数据库,并且ID是0。如果传入了这个参数会提示错误:

1
2
if "db" in kwargs:
raise RedisClusterException("Argument 'db' is not possible to use in cluster mode")

初始化完成后,就可以使用redis-py-cluster来操作Redis了,绝大多数API都是支持的,对于api的支持以及如何使用,可以参考其官方文档:redis-py-cluster。唉,本想好好写的,写了半天发现其实和python redis没有太大的区别,简单的介绍下如何实例化就行。