python连接redis哨兵_Python redis.sentinel方法代码示例

本文整理汇总了Python中redis.sentinel方法的典型用法代码示例。如果您正苦于以下问题:Python redis.sentinel方法的具体用法?Python redis.sentinel怎么用?Python redis.sentinel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块redis的用法示例。

在下文中一共展示了redis.sentinel方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _get_service_names

​点赞 6

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def _get_service_names(self): # type: () -> List[six.text_type]

"""

Get a list of service names from Sentinel. Tries Sentinel hosts until one succeeds; if none succeed,

raises a ConnectionError.

:return: the list of service names from Sentinel.

"""

master_info = None

connection_errors = []

for sentinel in self._sentinel.sentinels:

# Unfortunately, redis.sentinel.Sentinel does not support sentinel_masters, so we have to step

# through all of its connections manually

try:

master_info = sentinel.sentinel_masters()

break

except (redis.ConnectionError, redis.TimeoutError) as e:

connection_errors.append('Failed to connect to {} due to error: "{}".'.format(sentinel, e))

continue

if master_info is None:

raise redis.ConnectionError(

'Could not get master info from Sentinel\n{}:'.format('\n'.join(connection_errors))

)

return list(master_info.keys())

开发者ID:eventbrite,项目名称:pysoa,代码行数:25,

示例2: _get_connection

​点赞 6

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def _get_connection(self, index): # type: (int) -> redis.StrictRedis

if not 0 <= index < self._ring_size:

raise ValueError(

'There are only {count} hosts, but you asked for connection {index}.'.format(

count=self._ring_size,

index=index,

)

)

for i in range(self._sentinel_failover_retries + 1):

try:

return self._get_master_client_for(self._services[index])

except redis.sentinel.MasterNotFoundError:

self.reset_clients() # make sure we reach out to get master info again on next call

_logger.warning('Redis master not found, so resetting clients (failover?)')

if i != self._sentinel_failover_retries:

self._get_counter('backend.sentinel.master_not_found_retry').increment()

time.sleep((2 ** i + random.random()) / 4.0)

raise CannotGetConnectionError('Master not found; gave up reloading master info after failover.')

开发者ID:eventbrite,项目名称:pysoa,代码行数:22,

示例3: setUp

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def setUp(self):

""" Clear all spans before a test run """

self.recorder = tracer.recorder

self.recorder.clear_spans()

# self.sentinel = Sentinel([(testenv['redis_host'], 26379)], socket_timeout=0.1)

# self.sentinel_master = self.sentinel.discover_master('mymaster')

# self.client = redis.Redis(host=self.sentinel_master[0])

self.client = redis.Redis(host=testenv['redis_host'])

开发者ID:instana,项目名称:python-sensor,代码行数:12,

示例4: setUp

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def setUp(self):

pymemcache.client.Client(('localhost', 22122)).flush_all()

redis.from_url('unix:///tmp/limits.redis.sock').flushall()

redis.from_url("redis://localhost:7379").flushall()

redis.from_url("redis://:sekret@localhost:7389").flushall()

redis.sentinel.Sentinel([

("localhost", 26379)

]).master_for("localhost-redis-sentinel").flushall()

rediscluster.RedisCluster("localhost", 7000).flushall()

if RUN_GAE:

from google.appengine.ext import testbed

tb = testbed.Testbed()

tb.activate()

tb.init_memcache_stub()

开发者ID:alisaifee,项目名称:limits,代码行数:16,

示例5: test_storage_check

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def test_storage_check(self):

self.assertTrue(

storage_from_string("memory://").check()

)

self.assertTrue(

storage_from_string("redis://localhost:7379").check()

)

self.assertTrue(

storage_from_string("redis://:sekret@localhost:7389").check()

)

self.assertTrue(

storage_from_string(

"redis+unix:///tmp/limits.redis.sock"

).check()

)

self.assertTrue(

storage_from_string("memcached://localhost:22122").check()

)

self.assertTrue(

storage_from_string(

"memcached://localhost:22122,localhost:22123"

).check()

)

self.assertTrue(

storage_from_string(

"memcached:///tmp/limits.memcached.sock"

).check()

)

self.assertTrue(

storage_from_string(

"redis+sentinel://localhost:26379",

service_name="localhost-redis-sentinel"

).check()

)

self.assertTrue(

storage_from_string("redis+cluster://localhost:7000").check()

)

if RUN_GAE:

self.assertTrue(storage_from_string("gaememcached://").check())

开发者ID:alisaifee,项目名称:limits,代码行数:41,

示例6: setUp

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def setUp(self):

self.storage_url = 'redis+sentinel://localhost:26379'

self.service_name = 'localhost-redis-sentinel'

self.storage = RedisSentinelStorage(

self.storage_url,

service_name=self.service_name

)

redis.sentinel.Sentinel([

("localhost", 26379)

]).master_for(self.service_name).flushall()

开发者ID:alisaifee,项目名称:limits,代码行数:12,

示例7: setUp

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def setUp(self):

pymemcache.client.Client(('localhost', 22122)).flush_all()

redis.from_url("redis://localhost:7379").flushall()

redis.from_url("redis://:sekret@localhost:7389").flushall()

redis.sentinel.Sentinel([

("localhost", 26379)

]).master_for("localhost-redis-sentinel").flushall()

rediscluster.RedisCluster("localhost", 7000).flushall()

开发者ID:alisaifee,项目名称:limits,代码行数:10,

示例8: test_fixed_window_with_elastic_expiry_redis_sentinel

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def test_fixed_window_with_elastic_expiry_redis_sentinel(self):

storage = RedisSentinelStorage(

"redis+sentinel://localhost:26379",

service_name="localhost-redis-sentinel"

)

limiter = FixedWindowElasticExpiryRateLimiter(storage)

limit = RateLimitItemPerSecond(10, 2)

self.assertTrue(all([limiter.hit(limit) for _ in range(0, 10)]))

time.sleep(1)

self.assertFalse(limiter.hit(limit))

time.sleep(1)

self.assertFalse(limiter.hit(limit))

self.assertEqual(limiter.get_window_stats(limit)[1], 0)

开发者ID:alisaifee,项目名称:limits,代码行数:15,

示例9: get_connection

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def get_connection(self, is_read_only=False) -> redis.StrictRedis:

"""

Gets a StrictRedis connection for normal redis or for redis sentinel

based upon redis mode in configuration.

:type is_read_only: bool

:param is_read_only: In case of redis sentinel, it returns connection

to slave

:return: Returns a StrictRedis connection

"""

if self.connection is not None:

return self.connection

if self.is_sentinel:

kwargs = dict()

if self.password:

kwargs["password"] = self.password

sentinel = Sentinel([(self.host, self.port)], **kwargs)

if is_read_only:

connection = sentinel.slave_for(self.sentinel_service,

decode_responses=True)

else:

connection = sentinel.master_for(self.sentinel_service,

decode_responses=True)

else:

connection = redis.StrictRedis(host=self.host, port=self.port,

decode_responses=True,

password=self.password)

self.connection = connection

return connection

开发者ID:biplap-sarkar,项目名称:pylimit,代码行数:33,

示例10: get_atomic_connection

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def get_atomic_connection(self) -> Pipeline:

"""

Gets a Pipeline for normal redis or for redis sentinel based upon

redis mode in configuration

:return: Returns a Pipeline object

"""

return self.get_connection().pipeline(True)

开发者ID:biplap-sarkar,项目名称:pylimit,代码行数:10,

示例11: __init__

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def __init__(self):

if self.REDIS_SENTINEL:

sentinels = [tuple(s.split(':')) for s in self.REDIS_SENTINEL.split(';')]

self._sentinel = redis.sentinel.Sentinel(sentinels,

db=self.REDIS_SENTINEL_DB,

socket_timeout=0.1)

else:

self._redis = redis.Redis.from_url(self.rewrite_redis_url())

开发者ID:ybrs,项目名称:single-beat,代码行数:10,

示例12: _get_master_client_for

​点赞 5

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def _get_master_client_for(self, service_name): # type: (six.text_type) -> redis.StrictRedis

if service_name not in self._master_clients:

self._get_counter('backend.sentinel.populate_master_client').increment()

self._master_clients[service_name] = self._sentinel.master_for(service_name)

master_address = self._master_clients[service_name].connection_pool.get_master_address()

_logger.info('Sentinel master address: {}'.format(master_address))

return self._master_clients[service_name]

开发者ID:eventbrite,项目名称:pysoa,代码行数:10,

示例13: _get_redis_connection

​点赞 4

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def _get_redis_connection(self, group, shard):

"""

Create and return a Redis Connection for the given group

Returns:

redis.StrictRedis: The Redis Connection

Raises:

Exception: Passes through any exceptions that happen in trying to get the connection pool

"""

redis_group = self.__config.redis_urls_by_group[group][shard]

self.__logger.info(u'Attempting to connect to Redis for group "{}", shard "{}", url "{}"'.format(group, shard,

redis_group))

if isinstance(redis_group, PanoptesRedisConnectionConfiguration):

redis_pool = redis.BlockingConnectionPool(host=redis_group.host,

port=redis_group.port,

db=redis_group.db,

password=redis_group.password)

redis_connection = redis.StrictRedis(connection_pool=redis_pool)

elif isinstance(redis_group, PanoptesRedisSentinelConnectionConfiguration):

sentinels = [(sentinel.host, sentinel.port) for sentinel in redis_group.sentinels]

self.__logger.info(u'Querying Redis Sentinels "{}" for group "{}", shard "{}"'.format(repr(redis_group),

group, shard))

sentinel = redis.sentinel.Sentinel(sentinels)

master = sentinel.discover_master(redis_group.master_name)

password_present = u'yes' if redis_group.master_password else u'no'

self.__logger.info(u'Going to connect to master "{}" ({}:{}, password: {}) for group "{}", shard "{}""'

.format(redis_group.master_name, master[0], master[1], password_present, group, shard))

redis_connection = sentinel.master_for(redis_group.master_name, password=redis_group.master_password)

else:

self.__logger.info(u'Unknown Redis configuration object type: {}'.format(type(redis_group)))

return

self.__logger.info(u'Successfully connected to Redis for group "{}", shard "{}", url "{}"'.format(group,

shard,

redis_group))

return redis_connection

开发者ID:yahoo,项目名称:panoptes,代码行数:46,

示例14: __init__

​点赞 4

# 需要导入模块: import redis [as 别名]

# 或者: from redis import sentinel [as 别名]

def __init__(

self,

hosts=None, # type: Optional[Iterable[Union[six.text_type, Tuple[six.text_type, int]]]]

connection_kwargs=None, # type: Dict[six.text_type, Any]

sentinel_services=None, # type: Iterable[six.text_type]

sentinel_failover_retries=0, # type: int

sentinel_kwargs=None, # type: Dict[six.text_type, Any]

):

# type: (...) -> None

# Master client caching

self._master_clients = {} # type: Dict[six.text_type, redis.StrictRedis]

# Master failover behavior

if sentinel_failover_retries < 0:

raise ValueError('sentinel_failover_retries must be >= 0')

self._sentinel_failover_retries = sentinel_failover_retries

connection_kwargs = dict(connection_kwargs) if connection_kwargs else {}

if 'socket_connect_timeout' not in connection_kwargs:

connection_kwargs['socket_connect_timeout'] = 5.0 # so that we don't wait indefinitely during failover

if 'socket_keepalive' not in connection_kwargs:

connection_kwargs['socket_keepalive'] = True

if (

connection_kwargs.pop('ssl', False) or 'ssl_certfile' in connection_kwargs

) and 'connection_class' not in connection_kwargs:

# TODO: Remove this when https://github.com/andymccurdy/redis-py/issues/1306 is released

connection_kwargs['connection_class'] = _SSLSentinelManagedConnection

sentinel_kwargs = dict(sentinel_kwargs) if sentinel_kwargs else {}

if 'socket_connect_timeout' not in sentinel_kwargs:

sentinel_kwargs['socket_connect_timeout'] = 5.0 # so that we don't wait indefinitely connecting to Sentinel

if 'socket_timeout' not in sentinel_kwargs:

sentinel_kwargs['socket_timeout'] = 5.0 # so that we don't wait indefinitely if a Sentinel goes down

if 'socket_keepalive' not in sentinel_kwargs:

sentinel_kwargs['socket_keepalive'] = True

self._sentinel = redis.sentinel.Sentinel(

self._convert_hosts(hosts),

sentinel_kwargs=sentinel_kwargs,

**connection_kwargs

)

if sentinel_services:

self._validate_service_names(sentinel_services)

self._services = list(sentinel_services) # type: List[six.text_type]

else:

self._services = self._get_service_names()

super(SentinelRedisClient, self).__init__(ring_size=len(self._services))

开发者ID:eventbrite,项目名称:pysoa,代码行数:50,

注:本文中的redis.sentinel方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/532034.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

交换两个数组 差最小 java_如何交换两个等长整形数组使其数组和的差最小(C和java实现)...

1 importjava.util.Arrays;23 /**4 *5 *authorAdministrator6 *7 */8 public classTestUtil {9 private int[] arrysMin null;1011 private int[] arrysMax null;1213 private int matchNum 0;1415 private boolean hasMatched false;1617 /**18 * 返回数组的所有元素的总和…

python 判断子序列_Leetcode练习(Python):第392题:判断子序列:给定字符串 s 和 t ,判断 s 是否为 t 的子序列。...

题目&#xff1a;判断子序列&#xff1a;给定字符串 s 和 t &#xff0c;判断 s 是否为 t 的子序列。你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~ 500,000)&#xff0c;而 s 是个短字符串(长度 <100)。字符串的一个子序列是原始字符串删除一些(也可…

垂直串联六关节机器人调试手册_工业机器人有哪些应用你知道吗?

目前&#xff0c;工业机器人大部分集中于传统的焊接、喷涂等领域&#xff0c;我国工业机器人的核心部件和整机市场仍被国外垄断&#xff0c;工业机器人要面向整个智能制造市场&#xff0c;还需要具备应对整个智能制造过程中大多数工艺的能力&#xff0c;而工业互联网则是实现智…

flume avro java 发送数据_flume将数据发送到kafka、hdfs、hive、http、netcat等模式的使用总结...

1、source为http模式&#xff0c;sink为logger模式&#xff0c;将数据在控制台打印出来。conf配置文件如下&#xff1a;# Name the components on this agenta1.sources r1a1.sinks k1a1.channels c1# Describe/configure the sourcea1.sources.r1.type http #该设置表示接…

python三角函数拟合_使用python进行数据拟合最小化函数

这是我对这个问题的理解。首先&#xff0c;我通过以下代码生成一些数据import numpy as npfrom scipy.integrate import quadfrom random import randomdef boxmuller(x0,sigma):u1random()u2random()llnp.sqrt(-2*np.log(u1))z0ll*np.cos(2*np.pi*u2)z1ll*np.cos(2*np.pi*u2)r…

java url 本地文件是否存在_我的应用程序知道URL中是否存在文件会一直停止[重复]...

这个问题在这里已有答案&#xff1a;我试图写一个应用程序&#xff0c;如果在给定的URL中有一个文件&#xff0c;将字符串放在textview中&#xff0c;这是代码和崩溃信息&#xff0c;可能是什么错误&#xff1f;public class MainActivity extends AppCompatActivity {String u…

python枚举类的意义_用于ORM目的的python枚举类

编辑问题我正在尝试创建一个类工厂,它可以生成具有以下属性的枚举类&#xff1a;>从列表中初始化类允许值(即,它)自动生成&#xff01;).> Class创建自己的一个实例对于每个允许的值.>类不允许创建任何其他实例一旦上述步骤已完成(任何尝试这样做会导致异常).>类实…

java 生成校验验证码_java生成验证码并进行验证

一实现思路使用BufferedImage用于在内存中存储生成的验证码图片使用Graphics来进行验证码图片的绘制&#xff0c;并将绘制在图片上的验证码存放到session中用于后续验证最后通过ImageIO将生成的图片进行输出通过页面提交的验证码和存放在session中的验证码对比来进行校验二、生…

yy自动语音接待机器人_智能语音机器人落地产品有哪些?

据相关研究报告表明&#xff0c;在众多人工智能落地产品或者应用场景中&#xff0c;智能语音机器人无论从产品的成熟度还是应用的广泛度来说&#xff0c;都是人工智能行业最热门和最有前景的产品。智能语音机器人并不只是一款产品&#xff0c;它是所有智能语音系列产品的统称&a…

java资源文件获取属性_Java读写资源文件类Properties

Java中读写资源文件最重要的类是Properties1) 资源文件要求如下:1、properties文件是一个文本文件2、properties文件的语法有两种&#xff0c;一种是注释&#xff0c;一种属性配置。注 释&#xff1a;前面加上#号属性配置&#xff1a;以“键值”的方式书写一个属性的配置信息…

java被放弃了_为什么学Java那么容易放弃?

学习Java确实很容易就放弃&#xff0c;但是也很容易就学好&#xff0c;因为大多数人都是抱着试一试的心态&#xff0c;然后当后面就坚持不下去但是回过头来想一想&#xff0c;打游戏上分容易吗&#xff0c;一样是磕磕碰碰的&#xff0c;有时候十几连跪都不会放弃你上分的心情。…

python 隐马尔科夫_机器学习算法之——隐马尔可夫(Hidden Markov ModelsHMM)原理及Python实现...

前言上星期写了Kaggle竞赛的详细介绍及入门指导&#xff0c;但对于真正想要玩这个竞赛的伙伴&#xff0c;机器学习中的相关算法是必不可少的&#xff0c;即使是你不想获得名次和奖牌。那么&#xff0c;从本周开始&#xff0c;我将介绍在Kaggle比赛中的最基本的也是运用最广的机…

java编程50_java经典50编程题(1-10)

1.有一对兔子从出生后第三个月起&#xff0c;每个月都生一对小兔子&#xff0c;小兔子长到三个月后每个月又生一对兔子&#xff0c;假设兔子不死亡&#xff0c;问每个月兔子的总数为多少&#xff1f;分析过程图片发自简书App示例代码图片发自简书App运行结果图片发自简书App反思…

python替代hadoop_Python连接Hadoop数据中遇到的各种坑(汇总)

最近准备使用PythonHadoopPandas进行一些深度的分析与机器学习相关工作。(当然随着学习过程的进展&#xff0c;现在准备使用PythonSparkHadoop这样一套体系来搭建后续的工作环境)&#xff0c;当然这是后话。但是这项工作首要条件就是将Python与Hadoop进行打通&#xff0c;本来认…

java 自动化测试_java写一个自动化测试

你模仿购物车试一下&#xff0c;同样是买东西&#xff0c;加上胜负平的赔率&#xff0c;输出改下应该就可以了package com.homework.lhh;import java.util.ArrayList;import java.util.Comparator;import java.util.Scanner;public class Ex04 {public static void main(String…

超大规模集成电路_纳米级超大规模集成电路芯片低功耗物理设计分析(二)

文 | 大顺简要介绍了功耗的组成&#xff0c;在此基础上从工艺、电路、门、系统四个层面探讨了纳米级超大规模集成电路的低功耗物理设计方法。关键词&#xff1a;纳米级&#xff1b;超大规模集成电路&#xff1b;电路芯片&#xff1b;电路设计02纳米级超大规模集成电路芯片低功耗…

java中的printnb_javaI/O系统笔记

1、File类File类的名字有一定的误导性&#xff1b;我们可能认为它指代的是文件&#xff0c;实际上却并非如此。它既能代表一个特定文件的名称&#xff0c;又能代表一个目录下的一组文件的名称。1.1、目录列表器如果需要查看目录列表&#xff0c;可以通过file.list(FilenameFilt…

outlook反应慢的原因_保险管怎么区分慢熔和快熔?

保险丝快熔与慢熔的区别所有双帽;对于这样的产品特性和安全性熔丝; gG的”&#xff0c;即&#xff0c;与接触帽组合接触;即&#xff0c;所述双(内/外盖)的盖。和一般的小型或地下加工厂&#xff0c;以便执行切割角&#xff0c;降低生产成本&#xff0c;这将选择单个帽铆接“单&…

java成员内部类_Java中的内部类(二)成员内部类

Java中的成员内部类(实例内部类)&#xff1a;相当于类中的一个成员变量&#xff0c;下面通过一个例子来观察成员内部类的特点public classOuter {//定义一个实例变量和一个静态变量private inta;private static intb;//定义一个静态方法和一个非静态方法public static voidsay(…

word 通配符_学会Word通配符,可以帮助我们批量处理好多事情

长文档需要批量修改或删除某些内容的时候&#xff0c;我们可以利用Word中的通配符来搞定这一切&#xff0c;当然&#xff0c;前提是你必须会使用它。通配符的功能非常强大&#xff0c;能够随意组合替换或删除我们定义的规则内容&#xff0c;下面易老师就分享一些关于查找替换通…