create an instance of the Redis class
181453
public static function forge($name = 'default', $config = array())
	{
		empty(static::$instances) and \Config::load('db', true);

		if ( ! ($conf = \Config::get('db.redis.'.$name)))
		{
			throw new \RedisException('Invalid instance name given.');
		}
		$config = \Arr::merge($conf, $config);

		static::$instances[$name] = new static($config);

		return static::$instances[$name];
	}
1151151
function connect() {
    if (!redis) {
      debug('createClient ' + key + ' at ' + host + ':' + port);
      redis = redisLib.createClient(port, host, redisOpts); }
  }
604322
def create(self, using=None, **kwargs):
        
        self._get_connection(using).indices.create(index=self._name, body=self.to_dict(), **kwargs)
1166424
async def create_redis_pool(address, *, db=None, password=None, ssl=None,
                            encoding=None, commands_factory=Redis,
                            minsize=1, maxsize=10, parser=None,
                            timeout=None, pool_cls=None,
                            connection_cls=None, loop=None):
    
    pool = await create_pool(address, db=db,
                             password=password,
                             ssl=ssl,
                             encoding=encoding,
                             minsize=minsize,
                             maxsize=maxsize,
                             parser=parser,
                             create_connection_timeout=timeout,
                             pool_cls=pool_cls,
                             connection_cls=connection_cls,
                             loop=loop)
    return commands_factory(pool)
219569
function createClient(testRedisUrl) {
  const redisUrl = testRedisUrl || REDIS_URL;

  if (!redisUrl) {
    return bluebird.reject(new Error('No Redis URL set'));
  }

  log('debug', `Connecting to Redis at ${redisUrl}`);

  return new bluebird(resolve => {
    module.exports.client = bluebird.promisifyAll(new Redis(redisUrl));
    module.exports.client.on('error', logGenericError(__filename));

    resolve({ server: redisUrl });
  });
}
1286900
def write(obj, data=None, **kwargs):
    
    if obj.REDIS_ENABLED_FOR_DYNACONF is False:
        raise RuntimeError(
            "Redis is not configured \n"
            "export REDIS_ENABLED_FOR_DYNACONF=true\n"
            "and configure the REDIS_FOR_DYNACONF_* variables"
        )
    client = StrictRedis(**obj.REDIS_FOR_DYNACONF)
    holder = obj.get("ENVVAR_PREFIX_FOR_DYNACONF")
    data = data or {}
    data.update(kwargs)
    if not data:
        raise AttributeError("Data must be provided")
    redis_data = {
        key.upper(): unparse_conf_data(value) for key, value in data.items()
    }
    client.hmset(holder.upper(), redis_data)
    load(obj)
367365
function createClient(redisClientOptions) {
  const client = redis.createClient(redisClientOptions);
  if (!client._options) {
    client._options = redisClientOptions;
  }
  return client;
}
1151930
def initialize(config):
    

    # Determine the client class to use
    if 'redis_client' in config:
        client = utils.find_entrypoint('turnstile.redis_client',
                                       config['redis_client'], required=True)
    else:
        client = redis.StrictRedis

    # Extract relevant connection information from the configuration
    kwargs = {}
    for cfg_var, type_ in REDIS_CONFIGS.items():
        if cfg_var in config:
            kwargs[cfg_var] = type_(config[cfg_var])

    # Make sure we have at a minimum the hostname
    if 'host' not in kwargs and 'unix_socket_path' not in kwargs:
        raise redis.ConnectionError("No host specified for redis database")

    # Look up the connection pool configuration
    cpool_class = None
    cpool = {}
    extra_kwargs = {}
    for key, value in config.items():
        if key.startswith('connection_pool.'):
            _dummy, _sep, varname = key.partition('.')
            if varname == 'connection_class':
                cpool[varname] = utils.find_entrypoint(
                    'turnstile.connection_class', value, required=True)
            elif varname == 'max_connections':
                cpool[varname] = int(value)
            elif varname == 'parser_class':
                cpool[varname] = utils.find_entrypoint(
                    'turnstile.parser_class', value, required=True)
            else:
                cpool[varname] = value
        elif key not in REDIS_CONFIGS and key not in REDIS_EXCLUDES:
            extra_kwargs[key] = value
    if cpool:
        cpool_class = redis.ConnectionPool

    # Use custom connection pool class if requested...
    if 'connection_pool' in config:
        cpool_class = utils.find_entrypoint('turnstile.connection_pool',
                                            config['connection_pool'],
                                            required=True)

    # If we're using a connection pool, we'll need to pass the keyword
    # arguments to that instead of to redis
    if cpool_class:
        cpool.update(kwargs)

        # Use a custom connection class?
        if 'connection_class' not in cpool:
            if 'unix_socket_path' in cpool:
                if 'host' in cpool:
                    del cpool['host']
                if 'port' in cpool:
                    del cpool['port']

                cpool['path'] = cpool['unix_socket_path']
                del cpool['unix_socket_path']

                cpool['connection_class'] = redis.UnixDomainSocketConnection
            else:
                cpool['connection_class'] = redis.Connection

        # Build the connection pool to use and set up to pass it into
        # the redis constructor...
        kwargs = dict(connection_pool=cpool_class(**cpool))

    # Build and return the database
    kwargs.update(extra_kwargs)
    return client(**kwargs)
973372
function initRedis(config, callback) {

  var self = this;

  protos.util.checkLocalPort(config.port, function(err) {

    if (err) {
      app.log("RedisTransport [%s:%s] %s", config.host, config.port, err.code);
    } else {

      // Set redis client
      self.client = redis.createClient(config.port, config.host, self.options);

      // Handle error event
      self.client.on('error', function(err) {
        callback.call(self, err);
      });

      // Authenticate if password provided
      if (typeof config.password == 'string') {
        self.client.auth(config.password, function(err, res) {
          if (err) {
            app.log("RedisTransport: [%s:%s] %s", config.host, config.port, err.code);
          } else if (typeof config.db == 'number' && config.db !== 0) {
            self.client.select(config.db, function(err, res) {
              if (err) callback.call(self, err);
              else callback.call(self, null);
            });
          } else {
            callback.call(self, null);
          }
        });
      } else if (typeof config.db == 'number' && config.db !== 0) {
        self.client.select(config.db, function(err, res) {
          callback.call(self, err);
        });
      } else {
        callback.call(self, null);
      }

    }
  });

}
114035
async def create_pool(settings: RedisSettings = None, *, _retry: int = 0) -> ArqRedis:
    
    settings = settings or RedisSettings()
    addr = settings.host, settings.port
    try:
        pool = await aioredis.create_redis_pool(
            addr,
            db=settings.database,
            password=settings.password,
            timeout=settings.conn_timeout,
            encoding='utf8',
            commands_factory=ArqRedis,
        )
    except (ConnectionError, OSError, aioredis.RedisError, asyncio.TimeoutError) as e:
        if _retry < settings.conn_retries:
            logger.warning(
                'redis connection error %s:%s %s %s, %d retries remaining...',
                settings.host,
                settings.port,
                e.__class__.__name__,
                e,
                settings.conn_retries - _retry,
            )
            await asyncio.sleep(settings.conn_retry_delay)
        else:
            raise
    else:
        if _retry > 0:
            logger.info('redis connection successful')
        return pool

    # recursively attempt to create the pool outside the except block to avoid
    # "During handling of the above exception..." madness
    return await create_pool(settings, _retry=_retry + 1)
1308882
protected function createRedisDriver()
    {
        $handler = $this->createCacheHandler('redis');

        $handler->getCache()->getStore()->setConnection(
            $this->app['config']['session.connection']
        );

        return $this->buildSession($handler);
    }
346472
def instance(self_or_cls,**params):
        

        if isinstance (self_or_cls,ParameterizedMetaclass):
            cls = self_or_cls
        else:
            p = params
            params = dict(self_or_cls.get_param_values())
            params.update(p)
            params.pop('name')
            cls = self_or_cls.__class__

        inst=Parameterized.__new__(cls)
        Parameterized.__init__(inst,**params)
        if 'name' in params:  inst.__name__ = params['name']
        else:                 inst.__name__ = self_or_cls.name
        return inst
817596
def initialize(name='', pool_size=10, host='localhost', password='', port=5432, user=''):
    

    global pool
    instance = Pool(name=name, pool_size=pool_size, host=host, password=password, port=port, user=user)
    pool = instance
    return instance
876682
function redis (redis) {
    // redis is being set
    if (defined(redis)) {
        // promisify redis if not already promisified
        if (!defined(redis.mgetAsync)) {
            throw new Error('redis must be promisified')
        }
        // create new cache instance
        this.cache = new ImmutableCoreModelCache({
            model: this,
            redis: redis,
        })
        // return model on set
        return this
    }
    // get existing redis client if any
    else if (defined(this.cache)) {
        return this.cache.redis
    }
}
622745
public function init() {
        if (!extension_loaded('redis')) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension is not loaded');
        }

        if (empty($this->host)) {
            throw new exception('sessionhandlerproblem', 'error', '', null,
                    '$CFG->session_redis_host must be specified in config.php');
        }

        // The session handler requires a version of Redis with the SETEX command (at least 2.0).
        $version = phpversion('Redis');
        if (!$version or version_compare($version, '2.0') <= 0) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension version must be at least 2.0');
        }

        $this->connection = new \Redis();

        $result = session_set_save_handler(array($this, 'handler_open'),
            array($this, 'handler_close'),
            array($this, 'handler_read'),
            array($this, 'handler_write'),
            array($this, 'handler_destroy'),
            array($this, 'handler_gc'));
        if (!$result) {
            throw new exception('redissessionhandlerproblem', 'error');
        }

        // MDL-59866: Add retries for connections (up to 5 times) to make sure it goes through.
        $counter = 1;
        $maxnumberofretries = 5;

        while ($counter <= $maxnumberofretries) {

            try {

                $delay = rand(100000, 500000);

                // One second timeout was chosen as it is long for connection, but short enough for a user to be patient.
                if (!$this->connection->connect($this->host, $this->port, 1, null, $delay)) {
                    throw new RedisException('Unable to connect to host.');
                }

                if ($this->auth !== '') {
                    if (!$this->connection->auth($this->auth)) {
                        throw new RedisException('Unable to authenticate.');
                    }
                }

                if (!$this->connection->setOption(\Redis::OPT_SERIALIZER, $this->serializer)) {
                    throw new RedisException('Unable to set Redis PHP Serializer option.');
                }

                if ($this->prefix !== '') {
                    // Use custom prefix on sessions.
                    if (!$this->connection->setOption(\Redis::OPT_PREFIX, $this->prefix)) {
                        throw new RedisException('Unable to set Redis Prefix option.');
                    }
                }
                if ($this->database !== 0) {
                    if (!$this->connection->select($this->database)) {
                        throw new RedisException('Unable to select Redis database '.$this->database.'.');
                    }
                }
                $this->connection->ping();
                return true;
            } catch (RedisException $e) {
                $logstring = "Failed to connect (try {$counter} out of {$maxnumberofretries}) to redis ";
                $logstring .= "at {$this->host}:{$this->port}, error returned was: {$e->getMessage()}";

                // @codingStandardsIgnoreStart
                error_log($logstring);
                // @codingStandardsIgnoreEnd
            }

            $counter++;

            // Introduce a random sleep between 100ms and 500ms.
            usleep(rand(100000, 500000));
        }

        // We have exhausted our retries, time to give up.
        return false;
    }
472859
async def create_session(self, **kwargs):
        
        self.opts.update(kwargs)
        self._session = aiohttp.ClientSession(**self.opts, loop=self._loop)
        if self.redis_opts:
            if aioredis:
                self._redis = await aioredis.create_redis(**self.redis_opts,
                                                          loop=self._loop)
            else:
                warnings.warn(no_redis_warning)
1073281
def MI_createInstance(self,
                          env,
                          instance):
        # pylint: disable=invalid-name
        

        logger = env.get_logger()
        logger.log_debug('CIMProvider MI_createInstance called...')
        rval = None
        ch = env.get_cimom_handle()
        cimClass = ch.GetClass(instance.classname,
                               instance.path.namespace,
                               LocalOnly=False,
                               IncludeQualifiers=True)
        # CIMOM has already filled in default property values for
        # props with default values, if values not supplied by client.
        rval = self.set_instance(env=env,
                                 instance=instance,
                                 previous_instance=None,
                                 cim_class=cimClass)
        rval = build_instance_name(rval, cimClass)
        logger.log_debug('CIMProvider MI_createInstance returning')
        return rval