本文整理汇总了Python中redis.sentinel.Sentinel.master_for方法的典型用法代码示例。如果您正苦于以下问题:Python Sentinel.master_for方法的具体用法?Python Sentinel.master_for怎么用?Python Sentinel.master_for使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类redis.sentinel.Sentinel
的用法示例。
在下文中一共展示了Sentinel.master_for方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __redis_client__
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def __redis_client__(self, instance):
try:
LOG.debug('Connecting to redis databaseinfra %s', self.databaseinfra)
# redis uses timeout in seconds
connection_timeout_in_seconds = Configuration.get_by_name_as_int('redis_connect_timeout', default=REDIS_CONNECTION_DEFAULT_TIMEOUT)
if (instance and instance.instance_type == Instance.REDIS) or (not self.databaseinfra.plan.is_ha and not instance):
connection_address, connection_port = self.__get_admin_single_connection(instance)
client = redis.Redis(host = connection_address,
port = int(connection_port),
password = self.databaseinfra.password,
socket_connect_timeout = connection_timeout_in_seconds)
else:
sentinels = self.__get_admin_sentinel_connection(instance)
sentinel = Sentinel(sentinels, socket_timeout=connection_timeout_in_seconds)
client = sentinel.master_for(self.databaseinfra.name,
socket_timeout=connection_timeout_in_seconds,
password = self.databaseinfra.password)
LOG.debug('Successfully connected to redis databaseinfra %s' % (self.databaseinfra))
return client
except Exception, e:
raise e
示例2: get_connection
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [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
示例3: get_redis_from_config
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def get_redis_from_config(settings, connection_class=Redis):
"""Returns a StrictRedis instance from a dictionary of settings.
To use redis sentinel, you must specify a dictionary in the configuration file.
Example of a dictionary with keys without values:
SENTINEL: {'INSTANCES':, 'SOCKET_TIMEOUT':, 'PASSWORD':,'DB':, 'MASTER_NAME':}
"""
if settings.get('REDIS_URL') is not None:
return connection_class.from_url(settings['REDIS_URL'])
elif settings.get('SENTINEL') is not None:
instances = settings['SENTINEL'].get('INSTANCES', [('localhost', 26379)])
socket_timeout = settings['SENTINEL'].get('SOCKET_TIMEOUT', None)
password = settings['SENTINEL'].get('PASSWORD', None)
db = settings['SENTINEL'].get('DB', 0)
master_name = settings['SENTINEL'].get('MASTER_NAME', 'mymaster')
sn = Sentinel(instances, socket_timeout=socket_timeout, password=password, db=db)
return sn.master_for(master_name)
kwargs = {
'host': settings.get('REDIS_HOST', 'localhost'),
'port': settings.get('REDIS_PORT', 6379),
'db': settings.get('REDIS_DB', 0),
'password': settings.get('REDIS_PASSWORD', None),
'ssl': settings.get('REDIS_SSL', False),
}
return connection_class(**kwargs)
示例4: get
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def get(self, location):
if location not in self.locations:
return 'Unknown Location'
colors = get_colors(location, self.config)
priceinfo = get_priceinfo(location, self.config)
if app.config['DEVEL']:
pool = redis.ConnectionPool(host='localhost', port=6379)
r = redis.Redis(connection_pool=pool)
else:
sentinel = Sentinel([('localhost', 26379)], socket_timeout=1)
r = sentinel.master_for('mymaster', socket_timeout=1)
beers = []
for key in r.keys('beer_{0}_*'.format(location)):
beer = convert(r.hgetall(key))
beer['beername'] = key
beers.append(beer)
if 'items' in priceinfo:
for beer in beers:
beer['price'] = '$ {0}'.format(' /'.join([beer[p].replace('.0', '') for p in priceinfo['items'] if p in beer]))
beers.sort(key=operator.itemgetter('brewery', 'name', 'type'))
return render_template(
'edit.html',
title='Beer List',
beers=beers,
location=location,
colors=colors,
roles=self.groups,
locations=self.locations,
priceinfo=priceinfo,
scroll=False
)
示例5: post
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def post(self, location):
if location not in self.locations:
return 'Unknown Location'
if app.config['DEVEL']:
pool = redis.ConnectionPool(host='localhost', port=6379)
r = redis.Redis(connection_pool=pool)
else:
sentinel = Sentinel([('localhost', 26379)], socket_timeout=1)
r = sentinel.master_for('mymaster', socket_timeout=1)
beers = {key: r.hgetall(key) for key in r.keys('beer_{0}_*'.format(location))}
for beername, beer in beers.items():
r.hset(beername, 'active', 'True' if beername in request.form.getlist('checks') else 'False')
for beer in request.form.getlist('delete'):
r.delete(beer)
r.save()
beers = []
for key in r.keys('beer_{0}_*'.format(location)):
beer = convert(r.hgetall(key))
beer['beername'] = key
beers.append(beer)
beers.sort(key=operator.itemgetter('brewery', 'name', 'type'))
return redirect(location)
示例6: TestApplication
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
class TestApplication(Application):
def __init__(self):
# Call to the superclass to bootstrap.
super(TestApplication, self).__init__(name='krux-redis-sentinel')
self.logger.debug('Parsing sentinels from args: %r', self.args.sentinel)
sentinels = hostports_from_args(self.args)
self.logger.debug('Parsed sentinel host, port pairs: %r', sentinels)
self.logger.debug('Initializing Sentinel instance...')
self.sentinel = Sentinel(sentinels, socket_timeout=SOCKET_TIMEOUT)
self.logger.debug('Initialized Sentinel instance: %r', self.sentinel)
def add_cli_arguments(self, parser):
add_sentinel_cli_arguments(parser)
def run(self):
master = self.sentinel.master_for(self.name)
slave = self.sentinel.slave_for(self.name)
try:
self.logger.info('Ping master: %s', master.ping())
except ConnectionError as err:
self.logger.warning('Could not connect to master!')
self.logger.error(err)
try:
self.logger.info('Ping slave: %s', slave.ping())
except ConnectionError as err:
self.logger.warning('Could not connect to slave!')
self.logger.error(err)
示例7: redis_client
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def redis_client():
if settings.CACHEOPS_REDIS and settings.CACHEOPS_SENTINEL:
raise ImproperlyConfigured("CACHEOPS_REDIS and CACHEOPS_SENTINEL are mutually exclusive")
client_class = CacheopsRedis
if settings.CACHEOPS_CLIENT_CLASS:
client_class = import_string(settings.CACHEOPS_CLIENT_CLASS)
if settings.CACHEOPS_SENTINEL:
if not {'locations', 'service_name'} <= set(settings.CACHEOPS_SENTINEL):
raise ImproperlyConfigured("Specify locations and service_name for CACHEOPS_SENTINEL")
sentinel = Sentinel(
settings.CACHEOPS_SENTINEL['locations'],
**omit(settings.CACHEOPS_SENTINEL, ('locations', 'service_name', 'db')))
return sentinel.master_for(
settings.CACHEOPS_SENTINEL['service_name'],
redis_class=client_class,
db=settings.CACHEOPS_SENTINEL.get('db', 0)
)
# Allow client connection settings to be specified by a URL.
if isinstance(settings.CACHEOPS_REDIS, six.string_types):
return client_class.from_url(settings.CACHEOPS_REDIS)
else:
return client_class(**settings.CACHEOPS_REDIS)
示例8: _init
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def _init(self, server, params):
super(CacheClass, self).__init__(params)
self._server = server
self._params = params
self.service_name = self.options.get("SERVICE_NAME", 'mymaster')
self.slave_read = self.options.get("READ_SLAVE", False)
if self.server:
def _get_hosttupe(conn):
host_lst = conn.rsplit(':', 1)
return host_lst[0], int(host_lst[1])
conn_list = [_get_hosttupe(conn) for conn in self.server]
else:
raise ImproperlyConfigured("sentinel server config error.")
kwargs = self.connection_pool_class_kwargs
max_connections = kwargs.pop('max_connections')
sentinel_manager = Sentinel(conn_list, sentinel_kwargs=kwargs)
kwargs.update({
'db': self.db,
'password': self.password,
'max_connections': max_connections
})
self._client = sentinel_manager.master_for(self.service_name,
connection_pool_class=self.connection_pool_class,
**kwargs)
if self.slave_read:
self._slave_client = sentinel_manager.slave_for(self.service_name,
connection_pool_class=self.connection_pool_class,
**kwargs)
示例9: run
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def run():
try:
logging.info('Calculating training booking reminders')
if SENTINEL_HOST is None:
client = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD)
else:
sentinel = Sentinel([(SENTINEL_HOST, SENTINEL_PORT)])
client = sentinel.master_for(SENTINEL_MASTER)
# When was the last time we notified for? Default to now
last_not_str = client.get(WEEK_LAST_CHECK)
now = datetime.datetime.now()
last_notified = now
if last_not_str is not None:
last_notified_date = dateutil.parser.parse(last_not_str)
# Check that this is after the current date
if last_notified_date > now:
last_notified = last_notified_date
# Now work out the date that is midnight one week and a day from now
one_week = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(8), datetime.time())
logging.info('Getting sessions from %s until %s' % (str(last_notified), str(one_week)))
if one_week <= last_notified:
return
# Find all the sessions that fall bewtween the last notified date and a weeks time
sessions = TrainingSession.query({
'find': {
'start': {
'$gte': last_notified,
'$lt': one_week
}
}
})
# Notify that these need reminding
for session in sessions:
data = {
'name': 'reminder',
'data': {
'type': 'trainingSession',
'data': session._id
}
}
client.rpush(EVENT_Q, json.dumps(data))
if (len(sessions) > 0):
client.publish(EVENT_CHAN, 'event')
logging.info('Published training booking events')
# Store that we've notified
client.set(WEEK_LAST_CHECK, one_week.isoformat())
logging.info('Finished training booking')
except Exception as ex:
logging.exception(ex)
示例10: check_sso_auth
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def check_sso_auth(user_id, brand_id, trans_type ):
sentinel = Sentinel([('120.76.154.208', 26379)], socket_timeout=0.5)
log.d(sentinel.discover_master('mymaster'))
redis_obj = sentinel.master_for('mymaster', socket_timeout=0.1)
db_obj = PostgreSQLConnector()
sso_cls = SSOAuth(redis_obj,db_obj)
return sso_cls.check_auth(user_id, brand_id, trans_type)
示例11: sso_log
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def sso_log(user_id, brand_id, trans_type, data_type,data_content,log_time):
sentinel = Sentinel([('112.74.198.224', 26379)], socket_timeout=0.5)
log.d(sentinel.discover_master('mymaster'))
redis_obj = sentinel.master_for('mymaster', socket_timeout=0.1)
db_obj = PostgreSQLConnector()
sso_cls = SSOAuth(redis_obj,db_obj)
return sso_cls.send_log(user_id, brand_id, trans_type, data_type,data_content,log_time)
示例12: redis_conn
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def redis_conn(readonly=True):
global sentinel, master_client, slave_client
if not sentinel:
sentinel = Sentinel(settings.REDIS_SENTINEL, socket_timeout=1)
if not master_client:
master_client = sentinel.master_for(settings.REDIS_CLUSTER)
if not slave_client:
slave_client = sentinel.slave_for(settings.REDIS_CLUSTER)
return slave_client if readonly else master_client
示例13: setUp
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def setUp(self):
sentinel = Sentinel(settings_test.REDIS_SENTINEL)
db = getattr(settings_test, 'REDIS_DB', 0)
self.connection = sentinel.master_for('mymaster', db=db)
self.connection.flushall()
self.guard = ContributionsGuard(self.connection)
self.anon_user = {'user_id': None, 'user_ip': '127.0.0.1'}
self.auth_user = {'user_id': 33, 'user_ip': None}
self.task = Task(id=22)
示例14: client
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def client(self):
sentinel = Sentinel(
self.sentinel_conf.get('sentinels'),
min_other_sentinels=self.sentinel_conf.get("min_other_sentinels", 0),
password=self.sentinel_conf.get("password"),
sentinel_kwargs={"socket_timeout": self.sentinel_conf.get("sentinel_timeout")},
)
return sentinel.master_for(self.sentinel_conf.get("service_name"), Redis,
socket_timeout=self.sentinel_conf.get("socket_timeout"))
示例15: _sentinel_managed_pool
# 需要导入模块: from redis.sentinel import Sentinel [as 别名]
# 或者: from redis.sentinel.Sentinel import master_for [as 别名]
def _sentinel_managed_pool(self):
sentinel = Sentinel(
self.sentinels,
min_other_sentinels=getattr(self, "min_other_sentinels", 0),
password=getattr(self, "password", None),
sentinel_kwargs={"socket_timeout": getattr(self, "sentinel_timeout", None)},
)
return sentinel.master_for(self.service_name, self.Client,
socket_timeout=self.socket_timeout).connection_pool