/** * @param string $host redis server host * @param int $port redis server port * @param int $database redis server database num * @param string $channel redis queue key * @param string $prefix prefix of redis queue key */ public function __construct($host = '127.0.0.1', $port = 6379, $database = 0, $channel = 'cache', $prefix = 'simple-fork-') { $this->redis = new \Redis(); $connection_result = $this->redis->connect($host, $port); if (!$connection_result) { throw new \RuntimeException('can not connect to the redis server'); } if ($database != 0) { $select_result = $this->redis->select($database); if (!$select_result) { throw new \RuntimeException('can not select the database'); } } if (empty($channel)) { throw new \InvalidArgumentException('channel can not be empty'); } $this->channel = $channel; if (empty($prefix)) { return; } $set_option_result = $this->redis->setOption(\Redis::OPT_PREFIX, $prefix); if (!$set_option_result) { throw new \RuntimeException('can not set the \\Redis::OPT_PREFIX Option'); } }
/** * Establishes a DB connection. * It does nothing if a DB connection has already been established. * @return \Redis * @throws Exception if connection fails */ public function open() { if ($this->_socket !== null) { return; } $connection = ($this->unixSocket ?: $this->hostname . ':' . $this->port) . ', database=' . $this->database; \Yii::trace('Opening redis DB connection: ' . $connection, __METHOD__); $this->_socket = new \Redis(); if ($this->unixSocket) { if ($this->persist) { $this->_socket->pconnect($this->unixSocket, $this->port, $this->dataTimeout); } else { $this->_socket->connect($this->unixSocket, $this->port, $this->dataTimeout); } } else { if ($this->persist) { $this->_socket->pconnect($this->hostname, $this->port, $this->dataTimeout); } else { $this->_socket->connect($this->hostname, $this->port, $this->dataTimeout); } } if (isset($this->password)) { if ($this->_socket->auth($this->password) === false) { throw new Exception('Redis authentication failed!'); } } $this->_socket->select($this->database); return $this->_socket; }
/** * Gets the redis client * @return Redis the redis client */ public function getClient() { if ($this->_client === null) { $this->_client = new Redis(); $this->_client->connect($this->hostname, $this->port); $this->_client->select($this->database); } return $this->_client; }
/** * Create queue * * @param array $options * @return Kue */ public function __construct(array $options = array()) { $this->injectors = $options + $this->injectors; $this->client =& $this->injectors['client']; if (!$this->client) { $this->client = new \Redis(); $this->client->connect($this->injectors['host'], $this->injectors['port']); if ($this->injectors['db']) { $this->client->select($this->injectors['db']); } } }
protected function _connect() { $this->_redis = new \Redis(); if ($this->_config['persistent']) { $this->_redis->pconnect($this->_config['host'], isset($this->_config['port']) ? $this->_config['port'] : null, isset($this->_config['timeout']) ? $this->_config['timeout'] : null); } else { $this->_redis->connect($this->_config['host'], isset($this->_config['port']) ? $this->_config['port'] : null, isset($this->_config['timeout']) ? $this->_config['timeout'] : null); } $this->_redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_NONE); if ($this->_config['database'] > 0) { $this->_redis->select($this->_config['database']); } }
/** * Return redis resource * * @return Redis */ public function getRedis() { if (!$this->redis) { $this->redis = new Redis(); if (isset($this->socket)) { $this->redis->connect($this->socket); } else { $this->redis->connect($this->host, $this->port); } $this->redis->select($this->database); } return $this->redis; }
/** * Get instance redis * * @return Redis */ public static function factory() { if (!self::$instance) { try { self::$instance = new Redis(); self::$instance->connect(Config::get('host'), Config::get('port'), Config::get('timeout')); self::$instance->select(Request::factory()->getDb()); } catch (RedisException $e) { throw $e; } } return self::$instance; }
/** * 设置连接 */ private function setConnection() { $this->connection = new \Redis(); $this->connection->connect($this->config_object->host(), $this->config_object->port()); $auth = $this->config_object->auth(); if (!empty($auth)) { $this->connection->auth($auth); } $database = $this->config_object->database(); if ($database != 0) { $this->connection->select($database); } }
/** * Gets the redis client * @return Redis the redis client */ public function getClient() { if ($this->_client === null) { $this->_client = new Redis(); $ret = $this->_client->connect($this->hostname, $this->port); if (isset($this->password)) { if ($this->_client->auth($this->password) === false) { throw new CException('Redis authentication failed!'); } } $this->_client->select($this->database); } return $this->_client; }
public function __construct($config) { if (!is_array($config) || array_key_exists('port', $config) && (!is_numeric($config['port']) || intval($config['port']) <= 0 || intval($config['port']) > 65535) || array_key_exists('index', $config) && (!is_numeric($config['index']) || intval($config['index']) < 0 || intval($config['index']) > 15) || array_key_exists('timeout', $config) && (!is_numeric($config['timeout']) || intval($config['timeout']) < 0)) { throw new \InvalidArgumentException(); } $ip = array_key_exists('ip', $config) ? $config['ip'] : self::DEFAULT_IP; $retry = false; $oriConfig = $ip; if (is_array($ip)) { if (count($ip) > 1) { $retry = true; } $tmpIdx = array_rand($ip); $ip = $ip[$tmpIdx]; unset($oriConfig[$tmpIdx]); } $port = array_key_exists('port', $config) ? intval($config['port']) : self::DEFAULT_PORT; $index = array_key_exists('index', $config) ? intval($config['index']) : self::DEFAULT_INDEX; $keepalive = array_key_exists('keepalive', $config) ? (bool) $config['keepalive'] : self::DEFAULT_KEEPALIVE; $timeout = array_key_exists('timeout', $config) ? doubleval($config['timeout']) / 1000 : self::DEFAULT_TIMEOUT; $instance = new \Redis(); $connectSucceeded = false; if ($keepalive) { $connectSucceeded = $instance->pconnect($ip, $port, $timeout); } else { $connectSucceeded = $instance->connect($ip, $port, $timeout); } if (!$connectSucceeded || !$instance->select($index)) { if ($retry) { $tmpIdx = array_rand($oriConfig); $ip = $oriConfig[$tmpIdx]; if ($keepalive) { $connectSucceeded = $instance->pconnect($ip, $port, $timeout); } else { $connectSucceeded = $instance->connect($ip, $port, $timeout); } if (!$connectSucceeded || !$instance->select($index)) { self::logConnectionError($config); throw new \RedisException(); } } else { self::logConnectionError($config); throw new \RedisException(); } } $this->redis = $instance; return; }
/** * @param unknown $database * * @throws \Mcustiel\SimpleCache\Drivers\phpredis\Exceptions\RedisConnectionException */ private function selectDatabase($database) { if (!is_integer($database) || $database < 0) { throw new RedisConnectionException("Can't select database '{$database}'. Should be a natural number."); } $this->connection->select($database); }
/** * Connects to a Redis server * * @return bool True if Redis server was connected */ protected function _connect() { try { $server = $this->_config['host']; if (empty($server) && !empty($this->_config['server'])) { $server = $this->_config['server']; } $this->_Redis = new \Redis(); if (!empty($this->settings['unix_socket'])) { $return = $this->_Redis->connect($this->settings['unix_socket']); } elseif (empty($this->_config['persistent'])) { $return = $this->_Redis->connect($this->_config['server'], $this->_config['port'], $this->_config['timeout']); } else { $persistentId = $this->_config['port'] . $this->_config['timeout'] . $this->_config['database']; $return = $this->_Redis->pconnect($this->_config['server'], $this->_config['port'], $this->_config['timeout'], $persistentId); } } catch (\RedisException $e) { return false; } if ($return && $this->_config['password']) { $return = $this->_Redis->auth($this->_config['password']); } if ($return) { $return = $this->_Redis->select($this->_config['database']); } return $return; }
public function process() { $this->params['output'] = 'json'; $context = \CADB\Model\Context::instance(); if (!($rdb = $context->getProperty('service.redis'))) { $this->result = array('found' => false, 'error' => "자동완성 기능이 활성화되어 있지 않습니다."); } else { if (!$this->params['q']) { $this->result = array('found' => false, 'error' => "자동완성할 키워드를 입력하세요."); } else { $redis = new \Redis(); try { $redis->connect('127.0.0.1', '6379', 2.5, NULL, 150); if ($redis->select($rdb) == false) { $this->result = array('found' => false, 'error' => "index 1 database 에 연결할 수 없습니다."); } else { $this->recommand = $redis->zRange($this->params['q'], 0, -1); if (@count($this->recommand)) { $this->result = array('found' => true, 'total_cnt' => @count($this->recommand)); } else { $this->result = array('found' => true, 'total_cnt' => 0); } } } catch (RedisException $e) { var_dump($e); } $redis->close(); } } }
public function connect() { if ($this->handler) { return $this->handler; } $config = $this->config; $handler = new \Redis(); // 优先使用unix socket $conn_args = $config['unix_socket'] ? array($config['unix_socket']) : array($config['host'], $config['port'], $config['timeout']); if ($this->isPersistent()) { $conn_args[] = $config['persistent_id']; $conn = call_user_func_array(array($handler, 'pconnect'), $conn_args); } else { $conn = call_user_func_array(array($handler, 'connect'), $conn_args); } if (!$conn) { throw new \Owl\Service\Exception('Cannot connect redis'); } if ($config['password'] && !$handler->auth($config['password'])) { throw new \Owl\Service\Exception('Invalid redis password'); } if ($config['database'] && !$handler->select($config['database'])) { throw new \Owl\Service\Exception('Select redis database[' . $config['database'] . '] failed'); } if (isset($config['prefix'])) { $handler->setOption(\Redis::OPT_PREFIX, $config['prefix']); } return $this->handler = $handler; }
public static final function openConnection($target) { if (empty(self::$redisInfo)) { self::parseConnectionInfo(); } $connection = new Redis(); if (isset(self::$redisInfo[$target])) { $info = self::$redisInfo[$target]; } else { $info = array('host' => '127.0.0.1', 'port' => 6379, 'timeout' => 0, 'database' => 0, 'password' => '', 'options' => array()); } try { $connection->connect($info['host'], $info['port'], $info['timeout']); if ($info['password']) { $connection->auth($info['password']); } $connection->select($info['database']); foreach ($info['options'] as $k => $v) { $connection->setOption($k, $v); } } catch (Exception $e) { $connection = null; } return $connection; }
/** * {@inheritdoc} */ public function getAdapter(array $config) { $client = new \Redis(); $dsn = $this->getDsn(); if (empty($dsn)) { if (false === $client->connect($config['host'], $config['port'])) { throw new ConnectException(sprintf('Could not connect to Redis database on "%s:%s".', $config['host'], $config['port'])); } } else { if (false === $client->connect($dsn->getFirstHost(), $dsn->getFirstPort())) { throw new ConnectException(sprintf('Could not connect to Redis database on "%s:%s".', $dsn->getFirstHost(), $dsn->getFirstPort())); } if (!empty($dsn->getPassword())) { if (false === $client->auth($dsn->getPassword())) { throw new ConnectException('Could not connect authenticate connection to Redis database.'); } } if ($dsn->getDatabase() !== null) { if (false === $client->select($dsn->getDatabase())) { throw new ConnectException(sprintf('Could not select Redis database with index "%s".', $dsn->getDatabase())); } } } $pool = new RedisCachePool($client); if (null !== $config['pool_namespace']) { $pool = new NamespacedCachePool($pool, $config['pool_namespace']); } return $pool; }
function initModules($application) { $redis = new Redis(); $redis->connect(CACHE_HOSTNAME, CACHE_PORT); $redis->select(CACHE_DB); $modulesKey = $application . '-modules'; $modules = $redis->get($modulesKey); if (empty($modules)) { $modules = []; $dir = __DIR__ . '/../../' . $application . '/modules'; $dirpath = realpath($dir); $filenames = scandir($dir); foreach ($filenames as $filename) { if ($filename == '.' || $filename == '..') { continue; } if (is_file($dirpath . DIRECTORY_SEPARATOR . $filename . '/Module.php')) { $modules[strtolower($filename)] = ['class' => $application . '\\modules\\' . $filename . '\\Module']; } } $redis->set($modulesKey, serialize([$modules, null])); } else { $modules = unserialize($modules); if (!empty($modules[0])) { $modules = $modules[0]; } } $redis->close(); return $modules; }
/** * Loads the configured driver and validates it. * @param array|string|bool $config custom configuration or config group name * @throws Kohana_Exception */ public function __construct($config = FALSE) { if (is_string($config)) { $name = $config; // Test the config group name if (($config = Kohana::config('redis.' . $config)) === NULL) { throw new Kohana_Exception('cache.undefined_group', $name); } } if (is_array($config)) { // Append the default configuration options $config += Kohana::config('redis.default'); } else { // Load the default group $config = Kohana::config('redis.default'); } // Cache the config in the object $this->config = $config; parent::connect($this->config['host'], $this->config['port'], $this->config['timeout']); if (!empty($config['auth'])) { parent::auth($config['auth']); } if (!empty($config['db'])) { parent::select($config['db']); } Kohana::log('debug', 'Redis Library initialized'); }
/** * Selects a database (if needed) using options in the given configuration array. * * @return bool True if the select succeeded or no database was specified, else false */ protected function _select() { if ($this->config['database']) { return $this->_connection->select($this->config['database']); } return true; }
public function connect($config) { $redis = new Redis(); $redis->connect($config['host'], $config['port']); $redis->select($config['db']); return $redis; }
/** * 链接到客户端 * @param array $options 链接配置信息 * @return void */ public function connection() { $client = $clientWrite = null; switch ($this->type) { case null: $client = $this->createConnection($this->getHost("read")); $clientWrite = $this->createConnection($this->getHost("write")); case "read": $client = $this->createConnection($this->getHost("read")); case "write": $client = $this->createConnection($this->getHost("write")); break; } if ($client === false || $clientWrite === false) { return $this->statu = false; } $this->client = $client; $this->clientWrite = $clientWrite; if (isset($this->client)) { $this->client->auth($this->options["password"]); $this->client->select($this->options["database"]); } if (isset($this->clientWrite)) { $this->clientWrite->auth($this->options["password"]); $this->clientWrite->select($this->options["database"]); } else { $this->clientWrite = $this->client; } return $this->statu = true; }
private function initializeCAS() { $casClient = new \CAS_Client(CAS_VERSION_2_0, true, Config::get('cas.hostname'), Config::get('cas.port'), Config::get('cas.context')); $casClient->setNoCasServerValidation(); if (true === Config::get('pgtservice.enabled', false)) { $casClient->setCallbackURL(Config::get('pgtservice.callback')); $casClient->setPGTStorage(new ProxyTicketServiceStorage($casClient)); } else { if (false !== Config::get('redis.hostname', false)) { $casClient->setCallbackURL($this->url->getURL() . '/callback.php'); $redis = new \Redis(); $redis->connect(Config::get('redis.hostname'), Config::get('redis.port', 6379), 2, null, 100); $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP); $redis->setOption(\Redis::OPT_PREFIX, Config::get('application.project_name') . ':PHPCAS_TICKET_STORAGE:'); $redis->select((int) Config::get('redis.hostname', 2)); $casClient->setPGTStorage(new RedisTicketStorage($casClient, $redis)); } else { $casClient->setCallbackURL($this->url->getURL() . '/callback.php'); $casClient->setPGTStorageFile(session_save_path()); // Handle logout requests but do not validate the server $casClient->handleLogoutRequests(false); } } // Accept all proxy chains $casClient->getAllowedProxyChains()->allowProxyChain(new \CAS_ProxyChain_Any()); return $casClient; }
/** * @param InputInterface $input Input * @param OutputInterface $output Output * * @return null */ public function execute(InputInterface $input, OutputInterface $output) { $redisHost = $input->getOption('host'); $redisPort = $input->getOption('port'); $redisDb = $input->getOption('db'); try { $config = Yaml::parse(file_get_contents($_SERVER['HOME'] . '/.hooks.yml')); } catch (\Exception $e) { $config = ['daemon' => ['host' => '127.0.0.1', 'port' => 6379, 'db' => 0]]; } if ($redisHost) { $config['daemon']['host'] = $redisHost; } if ($redisPort) { $config['daemon']['port'] = $redisPort; } if ($redisDb) { $config['daemon']['db'] = $redisDb; } $redis = new \Redis(); $redis->connect($config['daemon']['host'], $config['daemon']['port']); $redis->select($config['daemon']['db']); $version = $redis->incr('hooks.worker.version'); $output->writeln('<info>Worker version incremented: ' . $version . '.</info>'); return null; }
/** * Class constructor * * Setup Redis * * Loads Redis config file if present. Will halt execution * if a Redis connection can't be established. * * @return void * @see Redis::connect() */ public function __construct() { if (!$this->is_supported()) { log_message('error', 'Cache: Failed to create Redis object; extension not loaded?'); return; } $CI =& get_instance(); if ($CI->config->load('redis', TRUE, TRUE)) { $config = array_merge(self::$_default_config, $CI->config->item('redis')); } else { $config = self::$_default_config; } $this->_redis = new Redis(); try { if (!$this->_redis->connect($config['host'], $config['host'][0] === '/' ? 0 : $config['port'], $config['timeout'])) { log_message('error', 'Cache: Redis connection failed. Check your configuration.'); } if (isset($config['password']) && !$this->_redis->auth($config['password'])) { log_message('error', 'Cache: Redis authentication failed.'); } if (isset($config['database']) && $config['database'] > 0 && !$this->_redis->select($config['database'])) { log_message('error', 'Cache: Redis select database failed.'); } } catch (RedisException $e) { log_message('error', 'Cache: Redis connection refused (' . $e->getMessage() . ')'); } }
/** * @param int $database * @throws CM_Exception */ protected function _select($database) { $database = (int) $database; if (false === $this->_redis->select($database)) { throw new CM_Exception('Cannot select database `' . $database . '`.'); } }
function setup() { $redis = new Redis(); $redis->connect(REDIS_HOST, REDIS_PORT); $redis->select(REDIS_DB); $this->redis = $redis; }
/** * redis 实例化 * @param $name 连接那个redis * @param $pconnect 是否进行长连接 * @param $ping 是否进行 ping 检测 */ public static function instance($name, $pconnect = false, $ping = false) { try { //检查是否可用 if (self::ping($name, $ping)) { return self::$instanceObj[$name]; } } catch (\RedisException $e) { self::$instanceObj[$name] = null; } //检查实例是否存在 if (isset(self::$instanceObj[$name]) && self::$instanceObj[$name] instanceof \Redis) { return self::$instanceObj[$name]; } $redisConf = self::getRedisConf($name); $host = $redisConf['host']; $port = $redisConf['port']; $redis = new \Redis(); if ($pconnect) { $redis->pconnect($host, $port); } else { $redis->connect($host, $port); } if (isset($redisConf['dbIndex'])) { $redis->select(intval($redisConf['dbIndex'])); } self::$instanceObj[$name] = $redis; return self::$instanceObj[$name]; }
/** * 创建 Redis.io client * @param array $servers * @param array $options * @return array * @throw exception */ protected function createClients(array $servers, array $options = []) { $clients = []; try { foreach ($servers as $key_s => $server) { $redis = new \Redis(); //长连接为pconnect,长连接要注意执行close关闭 $func = Arr::get($server, 'persistent', false) ? 'pconnect' : 'connect'; $redis->connect(Arr::get($server, 'host', ''), Arr::get($server, 'port'), $this->timeOut); //有配置密码的,进行auth操作 if ($pwd = Arr::get($server, 'password', '')) { $redis->auth($pwd); } $redis->select(Arr::get($server, 'database')); //设置redis的option,如Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE foreach ($options as $key => $val) { $redis->setOption($key, $val); } $clients[$key_s] = $redis; } } catch (\Exception $e) { throw new \Exception("connect redis error:" . var_export($e->getMessage(), 1)); } return $clients; }
/** * * @param string $name * @param array $arguments * @return RedisFactory * @throws Exception */ public static function __callStatic($name, $arguments) { switch ($name) { case 'get': list($redis_name, ) = $arguments ? $arguments : array('normal'); if (!isset(self::$redis_list[$redis_name])) { $redis_list = Application::$configs['redis']; if (isset($redis_list[$redis_name])) { try { $redis_handle = new Redis(); $connected = $redis_handle->pconnect($redis_list[$redis_name]['host'], $redis_list[$redis_name]['port'], 30, sprintf('%s_%s_%s', $redis_list[$redis_name]['host'], $redis_list[$redis_name]['port'], $redis_list[$redis_name]['db'])); if (false == $connected) { throw new Exception(sprintf('can\'t connect %s redis %s', $redis_name, json_encode($redis_list[$redis_name]))); } $selected = $redis_handle->select((int) $redis_list[$redis_name]['db']); if (false == $selected) { throw new Exception(sprintf('connect %s redis %s select db failed', $redis_name, json_encode($redis_list[$redis_name]))); } self::$redis_list[$redis_name] = new self($redis_handle); } catch (RedisException $e) { throw new Exception($e->getMessage()); } } else { throw new Exception('no config data key `' . $redis_name . '`'); } } return self::$redis_list[$redis_name]; break; //其他case 省略 //其他case 省略 default: throw new Exception('RedisFactory unknown static method `' . $name . '`'); } }
private function create() { $this->instance = new \Redis(); // TODO allow configuring a RedisArray, see https://github.com/nicolasff/phpredis/blob/master/arrays.markdown#redis-arrays $config = $this->config->getValue('redis', array()); if (isset($config['host'])) { $host = $config['host']; } else { $host = '127.0.0.1'; } if (isset($config['port'])) { $port = $config['port']; } else { $port = 6379; } if (isset($config['timeout'])) { $timeout = $config['timeout']; } else { $timeout = 0.0; // unlimited } $this->instance->connect($host, $port, $timeout); if (isset($config['password']) && $config['password'] !== '') { $this->instance->auth($config['password']); } if (isset($config['dbindex'])) { $this->instance->select($config['dbindex']); } }