• python redis cluster


    在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

    Code your future.
  • 相关阅读:
    团队个人冲刺day08
    4.26 jQuery AJAX load() 方法
    4.23 jquery
    4.22 AJAX技术
    4.21 正则表达式
    4.20
    4.15 重写团队作业1
    4.12 重写团队作业1
    4.9 团队作业1
    4.7 团队作业1
  • 原文地址:https://www.cnblogs.com/neozheng/p/15187673.html
Copyright © 2020-2023  润新知