Connect to redis and assign the client to the RedisSession class
        so that it is globally available in this process.

        :param dict settings: The redis session configuration
195848
def _redis_connect(cls, settings):
        
        if 'tornadoredis' not in globals():
            import tornadoredis
        kwargs = {'host': settings.get('host', cls.REDIS_HOST),
                  'port': settings.get('port', cls.REDIS_PORT),
                  'selected_db': settings.get('db', cls.REDIS_DB)}
        LOGGER.info('Connecting to %(host)s:%(port)s DB %(selected_db)s',
                    kwargs)
        cls._redis_client = tornadoredis.Client(**kwargs)
        cls._redis_client.connect()
1265196
static void applyUriConnectionSettings(RedisURI from, RedisURI to) {

        if (from.getPassword() != null && from.getPassword().length != 0) {
            to.setPassword(new String(from.getPassword()));
        }

        to.setTimeout(from.getTimeout());
        to.setSsl(from.isSsl());
        to.setStartTls(from.isStartTls());
        to.setVerifyPeer(from.isVerifyPeer());
    }
831768
def patch_connection(filename=':memory:'):
    

    if no_redis:
        raise Exception("redis package not found, please install redis-py via 'pip install redis'")

    RliteConnection.set_file(filename)

    global orig_classes

    # already patched
    if orig_classes:
        return

    orig_classes = (redis.connection.Connection,
                    redis.connection.ConnectionPool)

    _set_classes(RliteConnection, RliteConnectionPool)
616525
def inject(clients={})
      @_injected_clients = true
      clients.each_pair do |name, client|
        _close_if_present(@_connections[name])
        @_connections[name] = Redis::Namespace.new(DEFAULT_NAMESPACE, redis: client)
      end
    end
393358
def _configure_connection(self, name, value):
    
    self.update("pg_settings", dict(setting=value), dict(name=name))
914587
async def connect(self):
        

        if isinstance(self.connection, dict):
            # a dict like {'host': 'localhost', 'port': 6379,
            #              'db': 0, 'password': 'pass'}
            kwargs = self.connection.copy()
            address = (
                kwargs.pop('host', 'localhost'),
                kwargs.pop('port', 6379)
            )
            redis_kwargs = kwargs
        elif isinstance(self.connection, aioredis.Redis):
            self._pool = self.connection
        else:
            # a tuple or list ('localhost', 6379)
            # a string "redis://host:6379/0?encoding=utf-8" or
            # a unix domain socket path "/path/to/redis.sock"
            address = self.connection
            redis_kwargs = {}

        if self._pool is None:
            async with self._lock:
                if self._pool is None:
                    self.log.debug('Connecting %s', repr(self))
                    self._pool = await self._create_redis_pool(
                        address, **redis_kwargs,
                        minsize=1, maxsize=100)

        return await self._pool
1085354
def get_redis_connection(config, use_strict_redis=False):
    
    redis_cls = redis.StrictRedis if use_strict_redis else redis.Redis

    if 'URL' in config:
        return redis_cls.from_url(config['URL'], db=config.get('DB'))

    if 'USE_REDIS_CACHE' in config.keys():

        try:
            # Assume that we're using django-redis
            from django_redis import get_redis_connection as get_redis
            return get_redis(config['USE_REDIS_CACHE'])
        except ImportError:
            pass

        from django.core.cache import caches
        cache = caches[config['USE_REDIS_CACHE']]
        # We're using django-redis-cache
        try:
            return cache._client
        except AttributeError:
            # For django-redis-cache > 0.13.1
            return cache.get_master_client()

    if 'UNIX_SOCKET_PATH' in config:
        return redis_cls(unix_socket_path=config['UNIX_SOCKET_PATH'], db=config['DB'])

    if 'SENTINELS' in config:
        sentinel_kwargs = {
            'db': config.get('DB'),
            'password': config.get('PASSWORD'),
            'socket_timeout': config.get('SOCKET_TIMEOUT'),
        }
        sentinel_kwargs.update(config.get('CONNECTION_KWARGS', {}))
        sentinel = Sentinel(config['SENTINELS'], **sentinel_kwargs)
        return sentinel.master_for(
            service_name=config['MASTER_NAME'], redis_class=redis_cls,
        )

    return redis_cls(host=config['HOST'], port=config['PORT'], db=config['DB'], password=config.get('PASSWORD'), ssl=config.get('SSL', False))
870237
def get_redis(**options):
    
    from uliweb import settings
    from uliweb.utils.common import log
    import redis
        
    options = (options or {})
    options.update(settings.REDIS)
    if 'unix_socket_path' in options:
        client = redis.Redis(unix_socket_path=options['unix_socket_path'])
    else:
        global __connection_pool__
    
        if not __connection_pool__ or __connection_pool__[0] != options['connection_pool']:
            d = {'host':'localhost', 'port':6379}
            d.update(options['connection_pool'])
            __connection_pool__ = (d, redis.ConnectionPool(**d))
        client = redis.Redis(connection_pool=__connection_pool__[1])
        
    if settings.REDIS.test_first:
        try:
            client.info()
        except Exception as e:
            log.exception(e)
            client = None
    return client
681498
def _redis_client(opts):
    '''
    
    '''
    redis_host = opts.get("eauth_redis_host", "localhost")
    redis_port = opts.get("eauth_redis_port", 6379)
    try:
        return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True)
    except rediscluster.exceptions.RedisClusterException as err:
        log.warning(
            'Failed to connect to redis at %s:%s - %s',
            redis_host, redis_port, err
        )
        return None
1227145
def _setup_stats(self):
        '''
        
        '''
        self.stats_dict = {}

        redis_conn = redis.Redis(host=self.settings['REDIS_HOST'],
                                 port=self.settings['REDIS_PORT'],
                                 db=self.settings.get('REDIS_DB'))

        try:
            redis_conn.info()
            self.logger.debug("Connected to Redis in StatsCollector Setup")
            self.redis_conn = redis_conn
        except ConnectionError:
            self.logger.warn("Failed to connect to Redis in StatsCollector"
                             " Setup, no stats will be collected")
            return

        if self.settings['STATS_TOTAL']:
            self._setup_stats_total(redis_conn)

        if self.settings['STATS_PLUGINS']:
            self._setup_stats_plugins(redis_conn)
1233137
def reconnect_redis(self):
        '''
        '''

        if self.shared_client and Storage.storage:
            return Storage.storage

        storage = Redis(
            port=self.context.config.REDIS_RESULT_STORAGE_SERVER_PORT,
            host=self.context.config.REDIS_RESULT_STORAGE_SERVER_HOST,
            db=self.context.config.REDIS_RESULT_STORAGE_SERVER_DB,
            password=self.context.config.REDIS_RESULT_STORAGE_SERVER_PASSWORD
        )

        if self.shared_client:
            Storage.storage = storage
        return storage
165313
def _new_redis_client(self):
        
        if 'tornadoredis' not in globals():
            import tornadoredis
        kwargs = self._redis_connection_settings()
        LOGGER.info('Connecting to %(host)s:%(port)s DB %(selected_db)s',
                    kwargs)
        return tornadoredis.Client(**kwargs)
487278
def setup_redis(self, crawler=None):
        
        if self.server is not None:
            return

        if crawler is None:
            # We allow optional crawler argument to keep backwards
            # compatibility.
            # XXX: Raise a deprecation warning.
            crawler = getattr(self, 'crawler', None)

        if crawler is None:
            raise ValueError("crawler is required")

        settings = crawler.settings

        if self.redis_key is None:
            self.redis_key = settings.get(
                'REDIS_START_URLS_KEY', defaults.START_URLS_KEY,
            )

        self.redis_key = self.redis_key % {'name': self.name}

        if not self.redis_key.strip():
            raise ValueError("redis_key must not be empty")

        if self.redis_batch_size is None:
            # TODO: Deprecate this setting (REDIS_START_URLS_BATCH_SIZE).
            self.redis_batch_size = settings.getint(
                'REDIS_START_URLS_BATCH_SIZE',
                settings.getint('CONCURRENT_REQUESTS'),
            )

        try:
            self.redis_batch_size = int(self.redis_batch_size)
        except (TypeError, ValueError):
            raise ValueError("redis_batch_size must be an integer")

        if self.redis_encoding is None:
            self.redis_encoding = settings.get('REDIS_ENCODING', defaults.REDIS_ENCODING)

        self.logger.info("Reading start URLs from redis key '%(redis_key)s' "
                         "(batch size: %(redis_batch_size)s, encoding: %(redis_encoding)s",
                         self.__dict__)

        self.server = connection.from_settings(crawler.settings)
        # The idle signal is called when the spider has no requests left,
        # that's when we will schedule new requests from redis queue
        crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)
710241
def __connect():
    
    global redis_instance
    if use_tcp_socket:
        redis_instance = redis.StrictRedis(host=hostname, port=port)
    else:
        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)
772600
function _createClient (name, options, callback) {
  const log = logger.child({ redis: name })
  log.debug('Redis creating client: ' + name)
  let isReady = false

  const config = {}
  deepAssign(config, _defaults, options)
  let client = redis.createClient(config)

  callback = _once(callback)
  _clients[ name ] = client
  _clients[ name ].log = log

  log.debug({ clients: Object.keys(_clients) }, 'Redis clients')

  client.on('error', function (err) {
    log.error({ err: err }, 'Redis client error')
    callback(err)
  })

  client.on('warning', function (err) {
    log.warn({ err: err }, 'Redis client warning')
  })

  client.on('connect', function () {
    log.debug('Redis connected: ' + name)
  })

  client.on('ready', function () {
    log.debug('Redis client ready: ' + name)
    log.debug({ config: config }, 'Redis client config')
    log.debug(`Redis server version: ${safeGet(() => client.server_info.redis_version)}`)
    isReady = true
    callback(null, client)
  })

  client.on('reconnecting', function () {
    log.debug('Redis client reconnecting: ' + name)
  })

  client.on('end', function () {
    log.debug('Redis client end: ' + name)
    // Close the connection before removing reference.
    client.quit()
    client = null
    delete _clients[ name ]
    log.debug({ clients: Object.keys(_clients) }, 'Redis clients: ' + _clients.length)
    if (!isReady) {
      callback(new Error('Done - Failed to connect to Redis'))
    }
  })
}
792405
def connect(self):
        
        self.connected_node = None

        for i, node in self.nodes.items():
            host, port = i.split(':')
            port = int(port)
            redis_client = redis.Redis(host, port, **self.client_kw_args)

            try:
                ret = redis_client.execute_command('HELLO')
                format_version, node_id = ret[0], ret[1]
                others = ret[2:]
                self.nodes[i] = Node(node_id, host, port, redis_client)
                self.connected_node = self.nodes[i]
            except redis.exceptions.ConnectionError:
                pass

        if not self.connected_node:
            raise ConnectionError('couldnt connect to any nodes')
        logger.info("connected to node %s" % self.connected_node)
537800
function init(){
    self.type = config.type || 'redis';
    if(config.redisMock){
      self.db = config.redisMock;
    }
    else{
      if(config.redisUrl){
        self.redisData = config.redisUrl || null;
      }
      else if(config.redisEnv){
        self.redisData = process.env[config.redisEnv] || null;
      }
      else if(config.redisData){
        self.redisData = config.redisData;
      }
      self.readOnly = (typeof config.readOnly === 'boolean') ? config.readOnly : false;
      try {
        if (self.redisData) {
          if(typeof self.redisData === 'string'){
            self.db = redis.createClient(self.redisData,
              {'no_ready_check': true,
              retry_strategy: retryStrategy});
          } else {
            self.db = redis.createClient(self.redisData.port,
              self.redisData.hostname, {'no_ready_check': true,
              retry_strategy: retryStrategy});

            // don't call redis auth method if no auth info passed
            if (self.redisData.auth) {
              self.db.auth(self.redisData.auth);
            }
          }
          self.db.on('error', function(err) {
            console.log('Error ' + err);
          });
          process.on('SIGTERM', function() {
            self.db.quit();
          });
          log(false, 'Redis client created with the following defaults:', {expiration: self.defaultExpiration, verbose: self.verbose, readOnly: self.readOnly});
        } else {
          self.db = false;
          log(false, 'Redis client not created: no redis config provided');
        }
      } catch (err) {
        self.db = false;
        log(true, 'Redis client not created:', err);
      }
    }
  }