Get Redis connection

        This property is awaitable.
345568
async def redis(self) -> aioredis.Redis:
        
        # Use thread-safe asyncio Lock because this method without that is not safe
        async with self._connection_lock:
            if self._redis is None:
                self._redis = await aioredis.create_redis_pool((self._host, self._port),
                                                               db=self._db, password=self._password, ssl=self._ssl,
                                                               minsize=1, maxsize=self._pool_size,
                                                               loop=self._loop, **self._kwargs)
        return self._redis
707425
def get_redis_info():
    """"""
    from kombu.utils.url import _parse_url as parse_redis_url
    from redis import (
        StrictRedis,
        ConnectionError as RedisConnectionError,
        ResponseError as RedisResponseError,
    )
    for conf_name in ('REDIS_URL', 'BROKER_URL', 'CELERY_BROKER_URL'):
        if hasattr(settings, conf_name):
            url = getattr(settings, conf_name)
            if url.startswith('redis://'):
                break
    else:
        log.error("No redis connection info found in settings.")
        return {"status": NO_CONFIG}
    _, host, port, _, password, database, _ = parse_redis_url(url)

    start = datetime.now()
    try:
        rdb = StrictRedis(
            host=host, port=port, db=database,
            password=password, socket_timeout=TIMEOUT_SECONDS,
        )
        info = rdb.info()
    except (RedisConnectionError, TypeError) as ex:
        log.error("Error making Redis connection: %s", ex.args)
        return {"status": DOWN}
    except RedisResponseError as ex:
        log.error("Bad Redis response: %s", ex.args)
        return {"status": DOWN, "message": "auth error"}
    micro = (datetime.now() - start).microseconds
    del rdb  # the redis package does not support Redis's QUIT.
    ret = {
        "status": UP, "response_microseconds": micro,
    }
    fields = ("uptime_in_seconds", "used_memory", "used_memory_peak")
    ret.update({x: info[x] for x in fields})
    return ret
127730
private Object getConnection()
    {
        /*
         * Jedis connection = factory.getConnection();
         * 
         * // If resource is not null means a transaction in progress.
         * 
         * if (settings != null) { for (String key : settings.keySet()) {
         * connection.configSet(key, settings.get(key).toString()); } }
         * 
         * if (resource != null && resource.isActive()) { return
         * ((RedisTransaction) resource).bindResource(connection); } else {
         * return connection; } if (resource == null || (resource != null &&
         * !resource.isActive()))
         */
        // means either transaction resource is not bound or it is not active,
        // but connection has already by initialized
        if (isBoundTransaction() && this.connection != null)
        {
            return this.connection;
        }

        // if running within transaction boundary.
        if (resource != null && resource.isActive())
        {
            // no need to get a connection from pool, as nested MULTI is not yet
            // supported.
            if (((RedisTransaction) resource).isResourceBound())
            {
                return ((RedisTransaction) resource).getResource();
            }
            else
            {
                Jedis conn = getAndSetConnection();
                return ((RedisTransaction) resource).bindResource(conn);
            }

        }
        else
        {
            Jedis conn = getAndSetConnection();
            return conn;
        }
    }
606016
def poll(self):
        """"""
        if self.redis_connected:
            json_item = request.get_json()
            result = None
            try:
                key = "rest:poll:{u}".format(u=json_item['poll_id'])
                result = self.redis_conn.get(key)

                if result is not None:
                    result = json.loads(result)
                    self.logger.debug("Found previous poll")
                    self.redis_conn.delete(key)
                    return self._create_ret_object(self.SUCCESS, result)
                else:
                    self.logger.debug("poll key does not exist")
                    return self._create_ret_object(self.FAILURE, None, True,
                                       "Could not find matching poll_id"), 404
            except ConnectionError:
                self.logger.error("Lost connection to Redis")
                self._spawn_redis_connection_thread()
            except ValueError:
                extras = {
                    "value": result
                }
                self.logger.warning('Unparseable JSON Received from redis',
                                                extra=extras)
                self.redis_conn.delete(key)
                return self._create_ret_object(self.FAILURE, None, True,
                                               "Unparseable JSON Received "
                                               "from redis"), 500
        self.logger.warn("Unable to poll redis, not connected")
        return self._create_ret_object(self.FAILURE, None, True,
                                       "Unable to connect to Redis"), 500
962732
function startAllConnections() {
  try {
    myUtils.validateConfig();
  }
  catch(e) {
    console.error(e.message);
    process.exit(2);
  }

  // redefine keys method before connections are started
  if (config.get('redis.useScan')) {
    console.log('Using scan instead of keys');
    Object.defineProperty(Redis.prototype, 'keys', {
      value: function(pattern, cb) {
        let keys = [];
        let that = this;
        let scanCB = function(err, res) {
          if (err) {
            if (typeof cb === 'function') cb(err);
            else {
              console.log('ERROR in redefined "keys" function to use "scan" instead without callback: ' + JSON.stringify(err));
            }
          }
          else {
            let count = res[0], curKeys = res[1];
            console.log("scanning: " + count + ": " + curKeys.length);
            keys = keys.concat(curKeys);
            if (Number(count) === 0) {
              if (typeof cb === 'function') cb(null, keys);
              else {
                console.log('ERROR in redefined "keys" function to use "scan" instead - no callback given!');
              }
            }
            else {
              that.scan(count, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
            }
          }
        };
        return this.scan(0, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
      }
    });
  }

  // first default connections from config object
  // second connection from cli params (redis-host, redis-port, ...)
  startDefaultConnections(config.connections, function (err) {
    if (err) {
      console.log(err);
      process.exit();
    }
    let db = parseInt(args['redis-db']);
    if (isNaN(db)) {
        db = 0;
    }

    let client;
    if (args['sentinel-host'] || args['sentinels'] || args['redis-host'] || args['redis-port'] || args['redis-socket'] || args['redis-password']) {
      let newDefault = {
        "label": config.get('redis.defaultLabel'),
        "dbIndex": db,
        "password": args['redis-password'] || '',
        "connectionName": config.get('redis.connectionName')
      };

      if (args['redis-socket']) {
        newDefault.path = args['redis-socket'];
      }
      else {
        newDefault.host = args['redis-host'] || "localhost";
        newDefault.port = args['redis-port'] || "6379";
        newDefault.sentinel_name = args['sentinel-name'];
        if (args['sentinels']) {
          newDefault.sentinels = myUtils.parseRedisSentinel('--sentinels', args['sentinels']);
        }
        else if (args['sentinel-host']) {
          newDefault.sentinels = myUtils.parseRedisSentinel( '--sentinel-host or --sentinel-port',
            args['sentinel-host'] + ':' + args['sentinel-port']);
        }
      }

      if (args['redis-tls']) {
        newDefault.tls = {};
      }

      if (!myUtils.containsConnection(config.connections, newDefault)) {
        client = myUtils.createRedisClient(newDefault);
        redisConnections.push(client);
        config.connections.push(newDefault);
        if (!config.get('noSave')) {
          myUtils.saveConnections(config,function (err) {
            if (err) {
              console.log("Problem saving connection config.");
              console.error(err);
            }
          });
        }
        setUpConnection(client, db);
      }
    } else if (config.connections.length === 0) {
      // fallback to localhost if nothing else configured
      client = myUtils.createRedisClient({label: config.get('redis.defaultLabel')});
      redisConnections.push(client);
      setUpConnection(client, db);
    }

    return startWebApp();
  });

  // wait a bit before starting browser to let http server start
  if (args['open']) {
    setTimeout(function() {
      let address = '127.0.0.1';
      if (config.get('server.address') !== '0.0.0.0' && config.get('server.address') !== '::') {
        address = config.get('server.address');
      }
      require('opener')('http://' + address + ':' + config.get('server.port'));
    }, 1000);
  }
}
1117505
def get(self, id):
        
        id = self.key_name(id)
        session_json = self.redis.get(id) or '{}'
        return json_loads(session_json)
242254
def wait_for_lock(self, lockname, locktime=60, auto_renewal=False):
        '''  '''
        pid = os.getpid()
        caller = inspect.stack()[0][3]
        try:
            # rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['host'], "port": settings.REDIS_SERVERS['std_redis']['port'], "db": settings.REDIS_SERVERS['std_redis']['db']}, ])
            rl = redis_lock.Lock(self, lockname, expire=locktime, auto_renewal=auto_renewal)
        except AssertionError:
            if self.logger:
                self.logger.error('Process {0} ({1}) could not get lock {2}. Going ahead without locking!!! {3}'.format(pid, caller, lockname, traceback.format_exc()))
            return False
        cont = 1
        t0 = time.time()
        lock = None
        while not lock:
            time.sleep(.05)
            cont += 1
            if cont % 20 == 0:
                if self.logger:
                    self.logger.debug('Process {0} ({1}) waiting for lock {2}. {3} seconds elapsed.'.format(pid, caller, lockname, time.time() - t0))
            # lock = rl.lock(lockname, locktime_ms)
            try:
                lock = rl.acquire()
            except RedisError:
                pass
        if self.logger:
            self.logger.debug('Process {0} ({1}) got lock {2} for {3} seconds'.format(pid, caller, lockname, locktime))
        return rl
964653
private AsyncConnections getConnections(Iterable<RedisURI> redisURIs) {

        AsyncConnections connections = new AsyncConnections();

        for (RedisURI redisURI : redisURIs) {
            if (redisURI.getHost() == null || connections.connectedNodes().contains(redisURI) || !isEventLoopActive()) {
                continue;
            }

            try {
                SocketAddress socketAddress = clientResources.socketAddressResolver().resolve(redisURI);

                ConnectionFuture<StatefulRedisConnection<String, String>> connectionFuture = nodeConnectionFactory
                        .connectToNodeAsync(CODEC, socketAddress);

                CompletableFuture<StatefulRedisConnection<String, String>> sync = new CompletableFuture<>();

                connectionFuture.whenComplete((connection, throwable) -> {

                    if (throwable != null) {

                        String message = String.format("Unable to connect to %s", socketAddress);
                        if (throwable instanceof RedisConnectionException) {
                            if (logger.isDebugEnabled()) {
                                logger.debug(throwable.getMessage(), throwable);
                            } else {
                                logger.warn(throwable.getMessage());
                            }
                        } else {
                            logger.warn(message, throwable);
                        }

                        sync.completeExceptionally(new RedisConnectionException(message, throwable));
                    } else {
                        connection.async().clientSetname("lettuce#ClusterTopologyRefresh");
                        sync.complete(connection);
                    }
                });

                connections.addConnection(redisURI, sync);
            } catch (RuntimeException e) {
                logger.warn(String.format("Unable to connect to %s", redisURI), e);
            }
        }

        return connections;
    }
699653
def get_redis_connection():
    
    if config.MOCK_REDIS:  # pragma: no cover
        import mockredis
        return mockredis.mock_strict_redis_client()  # pragma: no cover
    elif config.DEFENDER_REDIS_NAME:  # pragma: no cover
        try:
            cache = caches[config.DEFENDER_REDIS_NAME]
        except InvalidCacheBackendError:
            raise KeyError(INVALID_CACHE_ERROR_MSG.format(
                config.DEFENDER_REDIS_NAME))
        # every redis backend implement it own way to get the low level client
        try:
            # redis_cache.RedisCache case (django-redis-cache package)
            return cache.get_master_client()
        except AttributeError:
            # django_redis.cache.RedisCache case (django-redis package)
            return cache.client.get_client(True)
    else:  # pragma: no cover
        redis_config = parse_redis_url(config.DEFENDER_REDIS_URL)
        return redis.StrictRedis(
            host=redis_config.get('HOST'),
            port=redis_config.get('PORT'),
            db=redis_config.get('DB'),
            password=redis_config.get('PASSWORD'),
            ssl=redis_config.get('SSL'))
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()
802760
function getKeyDetailsString (key, redisConnection, data, next) {
  redisConnection.get(key, function (err, val) {
    if (err) {
      api.log('getRedisString: ' + err, 'error');
    }

    var details = {
      key: key,
      type: 'string',
      value: val
    };
    
    data.response.details = details;
    next();
  });
}
936860
async def _make_connection(self):
        """"""
        return await aioredis.create_redis(
            'redis://{}:{}'.format(
                self._redis_params.get('host', 'localhost'),
                self._redis_params.get('port', 6379)
            ),
            db=int(self._redis_params.get('db', 1))
        )
871134
async def connect(self):
        '''
        '''
        assert not self.closed
        connection = await self._get()
        return PoolConnection(self, connection)
864475
def get_connection(self, command_name, *keys, **options):
        """"""
        self._checkpid()
        try:
            connection = self._available_connections[self._pattern_idx].pop()
        except IndexError:
            connection = self.make_connection()
        self._in_use_connections[self._pattern_idx].add(connection)
        self._next_pattern()
        return connection
1213919
private function connection__redis() {
		$this->connection = new \Redis();
		# @note: This emits warning on failure instead of throwing
		# exception, hence the @ sign.
		if (!@$this->connection->connect(
			$this->redishost, $this->redisport,
			$this->redistimeout
		))
			// @codeCoverageIgnoreStart
			return $this->connection_open_fail();
			// @codeCoverageIgnoreEnd
		if ($this->redispassword || $this->redisdatabase) {
			try {
				if ($this->redispassword)
					$this->connection->auth($this->redispassword);
				if ($this->redisdatabase)
					$this->connection->select($this->redisdatabase);
			} catch(\RedisException $e) {
				return $this->connection_open_fail($e->getMessage());
			}
		}
		try {
			$this->connection->ping();
		} catch(\RedisException $e) {
			return $this->connection_open_fail($e->getMessage());
		}
		return $this->connection_open_ok();
	}
1351359
public function getRedis(): ?Connection
    {
        if (!$this->hasRedis()) {
            $this->setRedis($this->getDefaultRedis());
        }
        return $this->redis;
    }
1155216
public function connect() {
		if (!$this->_connect()) {
			throw new RedisSourceException(__d('redis', 'Could not connect.'));
		}

		if (!$this->_authenticate()) {
			throw new RedisSourceException(__d('redis', 'Could not authenticate.'));
		}

		if (!$this->_select()) {
			throw new RedisSourceException(__d('redis', 'Could not select.'));
		}

		if (!$this->_setPrefix()) {
			throw new RedisSourceException(__d('redis', 'Could not set prefix.'));
		}

		$this->connected = true;

		return $this->connected;
	}