ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

python redis cluster

2021-08-26 01:34:22  阅读:277  来源: 互联网

标签:python py redis rediscluster cluster client foo


在aws ElastiCache 搭建好了 redis集群,用 python 的 redis 包时,我用 ab 做了一下简单的压力测试,发现代码中有报错,如下所求:

redis.exceptions.ResponseError: MOVED 10581  172.31.xx.xxx:6379

 

在网上查资料,发现了如下原因:

当 Redis  是集群模式时,python 的  redis-py 模块就不能再使用了,会报上面出现的错误。

参考链接:

http://xiaorui.cc/archives/1453

而且,对于redis集群,只有当您“为某个密钥(key)找到所属的插槽(slot),然后找到每个主服务器所服务的插槽”时,才能使用普通的redis client。有了这些信息,我可以在没有移动重定向错误的情况下为正确的节点设置密钥(key)。

参考链接:

https://stackoverflow.com/questions/43208157/redis-exceptions-responseerror-moved-error-in-redis-set-operation

 

看样子要使用 redis-py-cluster了

安装 redis-py-cluster 及其简单的示例代码:

# 安装
pip install redis-py-cluster


>>> import rediscluster
>>> startup_nodes = [{ "host": “mycluster.cache.amazonaws.com”, "port": "6379" }]
>>> client = rediscluster.RedisCluster(startup_nodes=[dict(host="MYHOST", port=6379)], decode_responses=True, skip_full_coverage_check=True)

# Retrieve the slot mapping (equivalent of "CLUSTER SLOTS")
>>> client.cluster('slots')
# Calculate hash slot for the key 'foo'
>>> client.cluster('keyslot', 'foo')
12182
# We can set a key without regard for which shard it will be stored on
# as the Redis client SDK will manage this mapping for us.
>>> client.set('foo', 'bar')
True
>>> client.get('foo')
'bar'

参考链接:

https://aws.amazon.com/cn/blogs/database/work-with-cluster-mode-on-amazon-elasticache-for-redis/

redis-py-cluster 官方文档:

https://redis-py-cluster.readthedocs.io/en/master/

 

安装好 redis-py-cluster 之后的示例代码,下面用的是其 连接池,用法和 redis-py 的连接池类似:

import rediscluster

redis_conn_pool = rediscluster.ClusterBlockingConnectionPool(
    startup_nodes=[dict(host="your-redis-cluster-name.xxxxxx.clustercfg.cnw1.cache.amazonaws.com.cn", port=6379)],
    max_connections=62, 
    skip_full_coverage_check=True,
    timeout=30
)    # 先建立一个连接池

client = RedisCluster(connection_pool=redis_conn_pool)    # 实例化一个 RedisCluster 客户端(像是从连接池中取一条连接的感觉)


# 其他的详细的用法可以去参考官方文档,或者是去看其源码。其他的 ConnectionPool 类,可以自己去看源码去了解

 

官方文档可以深入研究一下:

https://redis.io/topics/cluster-spec

 

标签:python,py,redis,rediscluster,cluster,client,foo
来源: https://www.cnblogs.com/neozheng/p/15187673.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有