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.pswp.cn/news/532034.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/532034.shtml
英文地址,請注明出處:http://en.pswp.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;下面易老師就分享一些關于查找替換通…