本文整理汇总了Python中redis.sentinel.Sentinel类的典型用法代码示例。如果您正苦于以下问题:Python Sentinel类的具体用法?Python Sentinel怎么用?Python Sentinel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Sentinel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect
def connect(self, index=0, write=True):
"""
Creates a redis connection with connection pool.
"""
master_name, sentinel_hosts, db = self.parse_connection_string(self._connection_string)
sentinel_timeout = self._options.get('SENTINEL_TIMEOUT', 1)
sentinel = Sentinel(sentinel_hosts, socket_timeout=sentinel_timeout)
if write:
host, port = sentinel.discover_master(master_name)
else:
host, port = random.choice([sentinel.discover_master(master_name)] + sentinel.discover_slaves(master_name))
kwargs = {
"db": db,
"parser_class": self.parser_class,
"password": self._options.get('PASSWORD', None),
}
kwargs.update({'host': host, 'port': port, 'connection_class': Connection})
if 'SOCKET_TIMEOUT' in self._options:
kwargs.update({'socket_timeout': int(self._options['SOCKET_TIMEOUT'])})
kwargs.update(self._pool_cls_kwargs)
connection_pool = get_or_create_connection_pool(self._pool_cls, **kwargs)
connection = Redis(connection_pool=connection_pool)
return connection
示例2: redis_client
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)
示例3: get_connection
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
示例4: get_redis_from_config
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)
示例5: _connection
def _connection(self):
sentinel = Sentinel(self._sentinels,
socket_timeout=self._socket_timeout)
slave = sentinel.slave_for(self._sentinel_master,
socket_timeout=self._socket_timeout,
db=self._db)
return slave
示例6: __redis_client__
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
示例7: post
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)
示例8: get
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
)
示例9: TestApplication
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)
示例10: _init
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)
示例11: run
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)
示例12: check_sso_auth
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)
示例13: sso_log
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)
示例14: setUp
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)
示例15: redis_conn
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