/** * 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; }
/** * Connects to a Redis server * * @return bool True if Redis server was connected */ protected function _connect() { try { $hash = "{$this->settings['server']}:{$this->settings['port']}:{$this->settings['database']}"; if (!empty(self::$instances[$hash])) { $return = $this->_Redis = self::$instances[$hash]; } else { $this->_Redis = new Redis(); self::$instances[$hash] = $this->_Redis; if (!empty($this->settings['unix_socket'])) { $return = $this->_Redis->connect($this->settings['unix_socket']); } elseif (empty($this->settings['persistent'])) { $return = $this->_Redis->connect($this->settings['server'], $this->settings['port'], $this->settings['timeout']); } else { $persistentId = $this->settings['port'] . $this->settings['timeout'] . $this->settings['database']; $return = $this->_Redis->pconnect($this->settings['server'], $this->settings['port'], $this->settings['timeout'], $persistentId); } } } catch (RedisException $e) { $return = false; } if (!$return) { return false; } if ($this->settings['password'] && !$this->_Redis->auth($this->settings['password'])) { return false; } return $this->_Redis->select($this->settings['database']); }
/** * Returns the singleton instance of Redis. If no instance has * been created, a new instance will be created. * * $redis = Koredis::factory(); * * @return Kohana_Koredis **/ public static function factory() { if (!Kohana_Koredis::$redis) { // Make sure Redis installed if (!class_exists('Redis', FALSE)) { throw new Kohana_Exception('class Redis can not be found. make sure you have installed phpredis extension'); } Kohana_Koredis::$redis = new Redis(); // No config file found if (!Kohana::$config->load('koredis')) { Kohana_Koredis::$redis->pconnect('127.0.0.1', 6379, 1); } else { // Load config $config = Kohana::$config->load('koredis'); $host = isset($config['host']) && $config['host'] ? $config['host'] : '127.0.0.1'; $port = isset($config['port']) && $config['port'] ? $config['port'] : 6379; $timeout = isset($config['timeout']) && $config['timeout'] ? $config['timeout'] : 1; $pconnect = isset($config['pconnect']) && $config['pconnect'] ? $config['pconnect'] : false; // Persistent connection if ($pconnect === TRUE) { Kohana_Koredis::$redis->pconnect($host, $port, $timeout); } else { Kohana_Koredis::$redis->connect($host, $port, $timeout); } } } return Kohana_Koredis::$redis; }
/** * Return redis connection object * * @return mixed Redis connection object on success, void or boolean on failure * * @since 3.4 * * @throws RuntimeException */ protected function getConnection() { if (static::isSupported() == false) { return false; } $config = JFactory::getConfig(); $app = JFactory::getApplication(); $caching = (bool) $config->get('caching'); if ($caching == false) { return false; } $this->_persistent = $config->get('redis_persist', true); $server = array('host' => $config->get('redis_server_host', 'localhost'), 'port' => $config->get('redis_server_port', 6379), 'auth' => $config->get('redis_server_auth', null), 'db' => (int) $config->get('redis_server_db', null)); static::$_redis = new Redis(); if ($this->_persistent) { try { $connection = static::$_redis->pconnect($server['host'], $server['port']); $auth = !empty($server['auth']) ? static::$_redis->auth($server['auth']) : true; } catch (Exception $e) { } } else { try { $connection = static::$_redis->connect($server['host'], $server['port']); $auth = !empty($server['auth']) ? static::$_redis->auth($server['auth']) : true; } catch (Exception $e) { } } if ($connection == false) { static::$_redis = null; if ($app->isAdmin()) { JError::raiseWarning(500, 'Redis connection failed'); } return; } if ($auth == false) { if ($app->isAdmin()) { JError::raiseWarning(500, 'Redis authentication failed'); } return; } $select = static::$_redis->select($server['db']); if ($select == false) { static::$_redis = null; if ($app->isAdmin()) { JError::raiseWarning(500, 'Redis failed to select database'); } return; } try { static::$_redis->ping(); } catch (RedisException $e) { static::$_redis = null; if ($app->isAdmin()) { JError::raiseWarning(500, 'Redis ping failed'); } return; } return static::$_redis; }
/** * If you want to use your own instance of Redis then pass it to UaiCachePhpredis::$redis before calling UserAgentInfoPeer for the first time. */ public static function autoInit() { if (self::$redis instanceof Redis) { return; } self::$redis = new Redis(); self::$redis->pconnect('127.0.0.1'); self::$redis->setOption(Redis::OPT_SERIALIZER, UserAgentInfoConfig::CACHE_USE_IGBINARY ? Redis::SERIALIZER_IGBINARY : Redis::SERIALIZER_PHP); }
/** * {@inheritDoc} * * @link https://github.com/phpredis/phpredis#pconnect-popen */ public function addServer($host, $port) { try { $this->_connection->pconnect($host, $port); } catch (\RedisException $e) { // TODO: since memcache/memcached adapters do not throw exceptions because // their connection are established lazily, this exception must unfortunately need to be swallowed } }
/** * @param $config * @throws TXException */ private function __construct($config) { $this->handler = new Redis(); if (isset($config['keep-alive']) && $config['keep-alive']) { $fd = $this->handler->pconnect($config['host'], $config['port'], TXConst::minute); } else { $fd = $this->handler->connect($config['host'], $config['port']); } if (!$fd) { throw new TXException(4005, array($config['host'], $config['port'])); } }
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']); } }
/** * Connects to a Redis server * * @return boolean True if Redis server was connected */ protected function _connect() { $return = false; try { $this->_Redis = new Redis(); if (empty($this->settings['persistent'])) { $return = $this->_Redis->connect($this->settings['server'], $this->settings['port'], $this->settings['timeout']); } else { $return = $this->_Redis->pconnect($this->settings['server'], $this->settings['port'], $this->settings['timeout']); } } catch (RedisException $e) { return false; } return $return; }
private function setupRedisConnection($config) { $this->redis = new \Redis(); if (isset($config['host'])) { $host = $config['host']; } else { $host = 'localhost'; } if (isset($config['port'])) { $port = $config['port']; $this->redis->pconnect($host, $port); } else { $this->redis->pconnect($host); } }
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; }
/** * 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]; }
public function connect($config = array('host' => '127.0.0.1', 'port' => 6379), $is_master = true) { //default port if (!isset($config['port'])) { $config['port'] = 6379; } //设置master链接 $redis = new Redis(); if ($redis) { $ret = $redis->pconnect($config['host'], $config['port']); //选择库 $redis->select(1); if ($is_master) { $this->_link_handle['master'] = $redis; } else { //多个slave链接 $this->_link_handle['slave'][$this->_slave_sn] = $redis; ++$this->_slave_sn; } return $ret; } else { echo 'redis fail'; return false; } }
/** * 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; }
/** * Retrieve Redis Cache Instance * * @return RedisCache|boolean */ public function init() { $redis_cache = false; $config = $this->getServiceLocator()->get('Config'); $config = $config['caches']['redis']; $namespace = $config['adapter']['options']['namespace']; $host = $config['adapter']['options']['server']['host']; $port = $config['adapter']['options']['server']['port']; $ttl = $config['adapter']['options']['ttl']; $redis = new \Redis(); /** * This is not required, although it will allow to store anything that * can be serialized by PHP in Redis */ try { $conn = $redis->pconnect($host, $port, $ttl); $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP); } catch (\Exception $e) { $conn = false; } if ($conn) { $redis_cache = new RedisCache(); $redis_cache->setNamespace($namespace); $redis_cache->setRedis($redis); } return $redis_cache; }
public function __construct() { /* require_once 'predis/autoload.php'; $redis_config = C('redis', 'redis'); try { $redis = new Predis\Client( "tcp://{$redis_config['hostname']}:{$redis_config['port']}"); $this->redis_instance = $redis; } catch (Exception $e) { echo "cannot connect to Redis server". PHP_EOL; echo $e->getMessage(); } */ $redis_config = C('redis', 'redis'); try { $redis = new Redis(); $redis->pconnect($redis_config['hostname'], $redis_config['port']); $this->redis_instance = $redis; } catch (Exception $e) { echo "cannot connect to Redis server" . PHP_EOL; echo $e->getMessage(); } }
/** * * @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 . '`'); } }
/** * Setup Redis config and connection * * Loads Redis config file if present. Will halt execution * if a Redis connection can't be established. * * @return bool * @see Redis::connect() */ protected function _setup_redis() { $config = array(); $CI =& get_instance(); if ($CI->config->load('redis', TRUE, TRUE)) { $config += $CI->config->item('redis'); } $config = array_merge(self::$_default_config, $config); $this->_redis = new Redis(); try { if ($config['socket_type'] === 'unix') { $success = $this->_redis->pconnect($config['socket']); } else { $success = $this->_redis->pconnect($config['host'], $config['port'], $config['timeout']); } if (!$success) { log_message('debug', 'Cache: Redis connection refused. Check the config.'); return FALSE; } } catch (RedisException $e) { log_message('debug', 'Cache: Redis connection refused (' . $e->getMessage() . ')'); return FALSE; } if (isset($config['password'])) { $this->_redis->auth($config['password']); } // Initialize the index of serialized values. $serialized = $this->_redis->sMembers('_ci_redis_serialized'); if (!empty($serialized)) { $this->_serialized = array_flip($serialized); } return TRUE; }
public function enqueueRequests() { if (!$this->has_requests) { return "No requests to send"; } $finished = "Error connecting to redis"; try { $redis = new Redis(); $redis->pconnect(REDIS_ADDRESS); $multi = $redis->multi(); //Executing all posts to Redis in one multi batch foreach ($this->data_requests as $key => $request) { $uuid = $request->getUUID(); $multi->lPush(PENDING_QUEUE, $uuid); $multi->hSet(VALUES_HASH, $uuid, $request->getFormattedURL()); $multi->hSet(VALUES_HASH, $uuid . ':method', $this->endpoint->method); $multi->hSet(STATS_HASH, $uuid . ':start', $this->start_time); } $ret = $multi->exec(); $finished = "Postback Delivered"; //Seach results for any errors from Redis commands foreach ($ret as $idx => $result) { if (!$result) { $finished = "Redis call failed: " . $idx; } } } catch (Exception $e) { return "Error posting to Redis"; } return $finished; }
/** * do driver instance init */ public function setup() { $settings = $this->getSettings(); if (empty($settings)) { throw new BoxRouteInstanceException('init driver instance failed: empty settings'); } $curInst = new \Redis(); $curHostInfo = explode(':', $settings['redisHost']); $host = $curHostInfo[0]; $port = isset($curHostInfo[1]) ? $curHostInfo[1] : null; if (intval($settings['redisPersistent']) != 0) { if (!empty($port)) { if (!empty($settings['redisConnectTimeout'])) { if (!$curInst->pconnect($host, $port, $settings['redisConnectTimeout'])) { throw new BoxRouteInstanceException('Instance init failed:could not connect'); } } else { if (!$curInst->pconnect($host, $port)) { throw new BoxRouteInstanceException('Instance init failed:could not connect'); } } } else { if (!$curInst->pconnect($host)) { throw new BoxRouteInstanceException('Instance init failed:could not connect'); } } } else { if (!empty($port)) { if (!empty($settings['redisConnectTimeout'])) { if (!$curInst->connect($host, $port, $settings['redisConnectTimeout'])) { throw new BoxRouteInstanceException('Instance init failed:could not connect'); } } else { if (!$curInst->connect($host, $port)) { throw new BoxRouteInstanceException('Instance init failed:could not connect'); } } } else { if (!$curInst->connect($host)) { throw new BoxRouteInstanceException('Instance init failed:could not connect'); } } } //$curInst->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); $this->instance = $curInst; $this->isAvailable = $this->instance ? true : false; }
protected function getInstance() { if (is_null($this->instance)) { $settings = $this->getOption(); $curInst = new Redis(); $curHostInfo = explode(':', $settings['redisHost']); $host = $curHostInfo[0]; $port = isset($curHostInfo[1]) ? $curHostInfo[1] : null; if (intval($settings['redisPersistent']) != 0) { if (!empty($port)) { if (!empty($settings['redisConnectTimeout'])) { if (!$curInst->pconnect($host, $port, $settings['redisConnectTimeout'])) { throw new \RuntimeException(_('Redis Usercache init Failed'), 500); } } else { if (!$curInst->pconnect($host, $port)) { throw new \RuntimeException(_('Redis Usercache init Failed'), 500); } } } else { if (!$curInst->pconnect($host)) { throw new \RuntimeException(_('Redis Usercache init Failed'), 500); } } } else { if (!empty($port)) { if (!empty($settings['redisConnectTimeout'])) { if (!$curInst->connect($host, $port, $settings['redisConnectTimeout'])) { throw new \RuntimeException(_('Redis Usercache init Failed'), 500); } } else { if (!$curInst->connect($host, $port)) { throw new \RuntimeException(_('Redis Usercache init Failed'), 500); } } } else { if (!$curInst->connect($host)) { throw new \RuntimeException(_('Redis Usercache init Failed'), 500); } } } //$curInst->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); $this->instance = $curInst; } return $this->instance; }
public static function debug($app) { // connect to the database $redis = new \Redis(); $redis->pconnect('127.0.0.1'); $data = $redis->get('debugdata'); echo json_encode($data); }
/** * Create the Redis connection * * @return Redis|boolean Redis connection object on success, boolean on failure * * @since 3.4 * @note As of 4.0 this method will throw a JCacheExceptionConnecting object on connection failure */ protected function getConnection() { if (static::isSupported() == false) { return false; } $config = JFactory::getConfig(); $app = JFactory::getApplication(); $this->_persistent = $config->get('redis_persist', true); $server = array('host' => $config->get('redis_server_host', 'localhost'), 'port' => $config->get('redis_server_port', 6379), 'auth' => $config->get('redis_server_auth', null), 'db' => (int) $config->get('redis_server_db', null)); static::$_redis = new Redis(); if ($this->_persistent) { try { $connection = static::$_redis->pconnect($server['host'], $server['port']); $auth = !empty($server['auth']) ? static::$_redis->auth($server['auth']) : true; } catch (RedisException $e) { JLog::add($e->getMessage(), JLog::DEBUG); } } else { try { $connection = static::$_redis->connect($server['host'], $server['port']); $auth = !empty($server['auth']) ? static::$_redis->auth($server['auth']) : true; } catch (RedisException $e) { JLog::add($e->getMessage(), JLog::DEBUG); } } if ($connection == false) { static::$_redis = null; throw new JCacheExceptionConnecting('Redis connection failed', 500); } if ($auth == false) { static::$_redis = null; throw new JCacheExceptionConnecting('Redis authentication failed', 500); } $select = static::$_redis->select($server['db']); if ($select == false) { static::$_redis = null; throw new JCacheExceptionConnecting('Redis failed to select database', 500); } try { static::$_redis->ping(); } catch (RedisException $e) { static::$_redis = null; throw new JCacheExceptionConnecting('Redis ping failed', 500); } return static::$_redis; }
function redis() { static $redis; if (!$redis) { $redis = new Redis(); $redis->pconnect('/tmp/redis.sock'); } return $redis; }
/** * @return \Redis */ protected function getRedis() { static $redis; if ($redis === null) { $redis = new \Redis(); $redis->pconnect($this->host, $this->port); } return $redis; }
/** * Конструктор класса * * @param bmApplication $application экземпляр текущего приложения * @param array $parameters параметры, необходимые для инициализации класса * @return bmCacheLink */ public function __construct($application, $parameters = array()) { parent::__construct($application, $parameters); $redis = new Redis(); $connectResult = $redis->pconnect('localhost'); if ($connectResult) { $this->cacher = $redis; } }
/** * 连接 redis * @param $redisConf */ private static function connect($redisConf, $pconnect) { $redis = new \Redis(); if ($pconnect) { $redis->pconnect($redisConf['host'], $redisConf['prot']); } else { $redis->connect($redisConf['host'], $redisConf['prot']); } return $redis; }
function NewRedisTestInstance() { $expecting = array('timeout' => 0); $r = new Redis(); $conn = $r->pconnect(REDIS_HOST, REDIS_PORT, $expecting['timeout']); var_dump($conn); $authok = REDIS_PASS ? $r->auth(REDIS_PASS) : true; var_dump($authok); return $r; }
function NewRedisTestInstance() { $expecting = array('timeout' => 0, 'database' => 0); $r = new Redis(); $persistentId = REDIS_PORT . $expecting['timeout'] . $expecting['database']; $conn = $r->pconnect(REDIS_HOST, REDIS_PORT, $expecting['timeout'], $persistentId); var_dump($conn); $authok = REDIS_PASS ? $r->auth(REDIS_PASS) : true; var_dump($authok); return $r; }
public function register(Kernel $kernel, $options = array()) { $kernel->redis = function () use($options) { $redis = new Redis(); $redis->pconnect($options['Host'], $options['Port']); if (isset($options['Password'])) { $redis->auth($options['Password']); } return $redis; }; }