• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sentinel.Sentinel类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了Sentinel类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:IthacaDream,项目名称:django-redis,代码行数:30,代码来源:sentinel.py


示例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)
开发者ID:Suor,项目名称:django-cacheops,代码行数:26,代码来源:redis.py


示例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
开发者ID:biplap-sarkar,项目名称:pylimit,代码行数:26,代码来源:redis_helper.py


示例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)
开发者ID:nvie,项目名称:rq,代码行数:27,代码来源:helpers.py


示例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
开发者ID:sumanthns,项目名称:quark,代码行数:7,代码来源:redis_client.py


示例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
开发者ID:mbergo,项目名称:database-as-a-service,代码行数:25,代码来源:redis.py


示例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)
开发者ID:taplists,项目名称:taplist,代码行数:27,代码来源:views.py


示例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
     )
开发者ID:taplists,项目名称:taplist,代码行数:31,代码来源:views.py


示例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)
开发者ID:krux,项目名称:python-krux-redis,代码行数:31,代码来源:sentinel.py


示例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)
开发者ID:a1401358759,项目名称:my_site,代码行数:34,代码来源:sentinel_backend.py


示例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)
开发者ID:ortoo,项目名称:reminders,代码行数:59,代码来源:training_bookings.py


示例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)
开发者ID:Aiwenada,项目名称:learngit,代码行数:8,代码来源:service.py


示例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)
开发者ID:Aiwenada,项目名称:learngit,代码行数:8,代码来源:service.py


示例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)
开发者ID:PyBossa,项目名称:pybossa,代码行数:9,代码来源:test_contributions_guard.py


示例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
开发者ID:yxteagle,项目名称:account,代码行数:9,代码来源:__init__.py


示例16: client

 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"))
开发者ID:ricobl,项目名称:rpaas,代码行数:9,代码来源:celery_sentinel.py


示例17: _sentinel_managed_pool

    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
开发者ID:titan-web,项目名称:RedisAdmin,代码行数:10,代码来源:celery_sentinel.py


示例18: __init__

	def __init__(self, **redis_conf):
		self.prefix = 'q'
		sentinels = redis_conf.pop('sentinels', '()')
		sentinels_service_name = redis_conf.pop('sentinels_service_name', 
				'mymaster')
		min_other_sentinels = redis_conf.pop('min_other_sentinels', 0)
		s = Sentinel(sentinels, **redis_conf)
		self.db = s.master_for(sentinels_service_name)
		#self.db = StrictRedis(**redis_conf)
		self.key = '%s:%s' % (self.prefix, '%s')
开发者ID:peeyush-tm,项目名称:shinken,代码行数:10,代码来源:module.py


示例19: get_redis_url

def get_redis_url():
    if hasattr(config, 'ETCD_HOST'):
        return config.HERA_REDIS_SENTINEL
    sentinel_list = [tuple(i.split(':')) for i in get_etcd_setting('HERA_REDIS_SENTINEL').split(',')]
    redis_db = get_etcd_setting('HERA_REDIS_DB')
    sentinel = Sentinel(sentinel_list, socket_timeout=0.1)
    master_name = get_etcd_setting('HERA_REDIS_MASTERNAME')
    return 'redis://{}/{}'.format(
        ':'.join(map(str, sentinel.discover_master(master_name))),
        redis_db
    )
开发者ID:liutaihua,项目名称:hera,代码行数:11,代码来源:util.py


示例20: new_new

    def new_new(_, cls, broker_url, *args, **kwargs):
        scheme = urlparse(broker_url).scheme
        if scheme == "redis-sentinel":
            from rpaas.tasks import app

            opts = app.conf.BROKER_TRANSPORT_OPTIONS
            s = Sentinel(opts["sentinels"], password=opts["password"])
            host, port = s.discover_master(opts["service_name"])
            return RedisBroker("redis://:{}@{}:{}".format(opts["password"], host, port))
        else:
            old_new(cls, broker_url, *args, **kwargs)
开发者ID:dmvieira,项目名称:rpaas,代码行数:11,代码来源:celery_sentinel.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python redis_cache.get_redis_connection函数代码示例发布时间:2022-05-26
下一篇:
Python redis.hset函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap