Inheritance: extends Illuminate\Support\Facades\Redis
Exemplo n.º 1
0
 /**
  * 创建 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;
 }
Exemplo n.º 2
0
 /**
  * 查看全部服务器
  */
 private function _overview_all()
 {
     $info = array();
     foreach ($this->server_list as $i => $server) {
         if (isset($server['cluster_list'])) {
             $info[$i]['error'] = FALSE;
             $info[$i]['cluster_list'] = $server['cluster_list'];
             continue;
         }
         $redis = new Redis();
         $can_connect = FALSE;
         try {
             $can_connect = $redis->connect($server['host'], $server['port'], 0.5);
         } catch (Exception $e) {
             $can_connect = TRUE;
         }
         $info[$i] = array('error' => FALSE);
         if (!$can_connect) {
             $info[$i]['error'] = TRUE;
         } else {
             $info[$i] = array_merge($info[$i], $redis->info());
             $info[$i]['size'] = $redis->dbSize();
         }
     }
     $page_data['info'] = $info;
     $page_data['server_list'] = $this->server_list;
     $page_data['title'] = '服务器一览表';
     $this->load->view('overview', $page_data);
 }
Exemplo n.º 3
0
 /**
  * {@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;
 }
Exemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 public function wait(Closure $callback)
 {
     while (true) {
         if (!$this->shouldProcessNext()) {
             break;
         }
         while (true) {
             $messageString = false;
             if ($this->redis instanceof \Predis\Client) {
                 $messageString = $this->redis->spop($this->key);
             }
             if ($this->redis instanceof \Redis) {
                 $messageString = $this->redis->sPop($this->key);
             }
             if (!$messageString) {
                 break;
             }
             $callback($this->serializer->unserialize($messageString));
             $this->incrementProcessedItems();
         }
         if ($this->refreshInterval) {
             sleep($this->refreshInterval);
         }
     }
 }
Exemplo n.º 5
0
 /**
  *
  * @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 . '`');
     }
 }
Exemplo n.º 6
0
 /**
  * 获取redis对象
  *
  * @return Redis
  */
 public static function get_redis()
 {
     $redis_conf = $GLOBALS['config']['redis'];
     $redis = new Redis();
     $res = $redis->connect($redis_conf['host'], $redis_conf['port']);
     return $redis;
 }
Exemplo n.º 7
0
 protected function cache()
 {
     $redis = new Redis();
     $redis->connect('127.0.0.1', 6379);
     $redis->auth('123456');
     return $redis;
 }
 public function testIfCacheInitsWithOpenConnection()
 {
     $redis = new \Redis();
     $redis->connect(REDIS_HOST, REDIS_PORT, REDIS_TIMEOUT_SECONDS);
     $this->cache = new RedisCache($redis);
     $this->assertKeysCanBeWrittenAndRead();
 }
Exemplo n.º 9
0
 /**
  * Get message with message not found
  */
 public function testGetMessageWithNoExistsMessage()
 {
     $this->redis->expects($this->once())->method('lPop')->with('foo.bar')->will($this->returnValue(false));
     $adapter = new RedisAdapter();
     $adapter->setRedis($this->redis)->setListKey('foo.bar');
     $this->assertNull($adapter->getMessage());
 }
Exemplo n.º 10
0
 public function getCacheAction()
 {
     $redis = new Redis();
     $redis->connect('127.0.0.1');
     $page = $redis->get('page');
     print_r($page);
 }
Exemplo n.º 11
0
 public static function class_init()
 {
     /** @var Settings $settings */
     $settings = resource(Settings::class);
     self::$redis = new \Redis();
     self::$redis->connect($settings->get("redis", "hostname"), $settings->get("redis", "connect_port"));
 }
/**
*@author: JJyy
*@todo: get the indirect transform number for the user_id 
*		less than 30 days
*@param: 
*
**/
function o_indirect_tsf($user_id, $channel_name, $timeset, $db)
{
    $sql = "select count(order_id) as cn from order_info where order_status=1 and pay_status=2 and confirm_time>" . $timeset . " and confirm_time<" . ($timeset + 3600 * 30);
    $row = $db->query($sql);
    $cn = $row['cn'];
    if ($cn == 0) {
        //if within 30 days no order
        return 0;
    } else {
        $rds = new Redis();
        //get the keys for the user_id
        $keys = $rds->keys("*:" . $user_id);
        //string like: li9t209jm7mc6m4vmn88o5a7j0:1454035403.8093:10.10.10.29:baidu:0
        $num = 0;
        foreach ($keys as $k => $v) {
            //the time must after timeset
            //same user_id and different channel_name and time after than timeset
            if ($v[1] > $timeset && $v[3] != $channel_name && $v[4] == $user_id) {
                $sql = "select count(order_id) as cn from order_info where order_status=1 and pay_status=2 and confirm_time>" . $timeset . " and confirm_time<" . ($timeset + 3600 * 2);
                $row = $db->query($sql);
                $cn = $row['cn'];
                $num += $cn;
            }
        }
        return $num;
    }
}
Exemplo n.º 13
0
 public function testBasics()
 {
     if (extension_loaded('Redis')) {
         $redis = new \Redis();
         try {
             $ok = @$redis->connect('127.0.0.1', 6379);
         } catch (\Exception $e) {
             $ok = false;
         }
         if (!$ok) {
             $this->markTestSkipped('The ' . __CLASS__ . ' cannot connect to redis');
         }
     } else {
         $this->markTestSkipped('The ' . __CLASS__ . ' requires the use of redis');
     }
     $cache = new RedisCache();
     $cache->setRedis($redis);
     // Test save
     $cache->save('test_key', 'testing this out');
     // Test contains to test that save() worked
     $this->assertTrue($cache->contains('test_key'));
     $cache->save('test_key1', 'testing this out', 20);
     // Test contains to test that save() worked
     $this->assertTrue($cache->contains('test_key1'));
     // Test fetch
     $this->assertEquals('testing this out', $cache->fetch('test_key'));
     // Test delete
     $cache->save('test_key2', 'test2');
     $cache->delete('test_key2');
     $this->assertFalse($cache->contains('test_key2'));
     $this->assertEquals($redis, $cache->getRedis());
 }
Exemplo n.º 14
0
 /**
  * Отключение от Redis.
  * 
  * @return void
  * @access public
  * @static
  */
 public static function close()
 {
     if (static::$redis) {
         static::$redis->close();
         static::$redis = null;
     }
 }
Exemplo n.º 15
0
 public function createRedis()
 {
     $redis = new \Redis();
     $redis->connect($this->getOption('host'), $this->getOption('port'));
     $redis->setOption(\Redis::OPT_PREFIX, $this->getOption('prefix'));
     return $redis;
 }
Exemplo n.º 16
0
 public function connect($config)
 {
     $redis = new Redis();
     $redis->connect($config['host'], $config['port']);
     $redis->select($config['db']);
     return $redis;
 }
Exemplo n.º 17
0
 public function testSetInstanceSuccess()
 {
     $driver = $this->getDriver();
     $client = new \Redis();
     $client->connect('localhost');
     $driver->setInstance($client);
 }
Exemplo n.º 18
0
 /**
  * @site http://www.chenliujin.com
  * @author chenliujin <*****@*****.**>
  * @since 2016-01-19
  * @param type $key
  */
 public static function Read($key)
 {
     $redis = new Redis();
     $redis->connect('127.0.0.1', 6379);
     $val = $redis->get($key);
     return $val ? $val : '';
 }
Exemplo n.º 19
0
 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;
 }
Exemplo n.º 20
0
/**
 * Must be defined before including bootstrap.php
 * as this is the only custom part in the example.
 */
function get_driver()
{
    $redis = new Redis();
    $redis->connect('localhost');
    $redis->setOption(Redis::OPT_PREFIX, 'bernard:');
    return new PhpRedisDriver($redis);
}
Exemplo n.º 21
0
function conn_redis()
{
    $redis = new Redis();
    $redis->connect('localhost', '6379');
    $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
    return $redis;
}
Exemplo n.º 22
0
 public function testRedisShouldWorkProperly()
 {
     $redis = new \Redis();
     $redis->connect('localhost');
     $this->assertTrue($redis->set('test', 'test'), 'The set method return false');
     $this->assertEquals('test', $redis->get('test'), 'The get method it\'s broken');
 }
Exemplo n.º 23
0
 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;
 }
Exemplo n.º 24
0
 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;
 }
Exemplo n.º 25
0
 public function __construct($redis = FALSE, $opts = array())
 {
     if (is_array($redis)) {
         $opts = $redis;
         $redis = FALSE;
     }
     // Apply default arguments
     $opts = array_merge(array('host' => 'localhost', 'port' => 6379), $opts);
     if (!$redis) {
         // Default to phpredis
         if (extension_loaded('redis')) {
             if (!isset($opts['socket']) && !isset($opts['host'])) {
                 throw new \Exception('Host should be provided when not providing a redis instance');
             }
             if (!isset($opts['socket']) && !isset($opts['port'])) {
                 throw new \Exception('Port should be provided when not providing a redis instance');
             }
             $redis = new \Redis();
             if (isset($opts['socket'])) {
                 $redis->connect($opts['socket']);
             } else {
                 $redis->connect($opts['host'], $opts['port']);
             }
         } else {
             $redis = new \TinyRedisClient($opts['host'] . ':' . $opts['port']);
         }
     }
     if (!is_callable(array($redis, 'publish'))) {
         throw new \Exception('The Redis client provided is invalid. The client needs to implement the publish method. Try using the default client.');
     }
     $this->redis = $redis;
     $this->key = (isset($opts['key']) ? $opts['key'] : 'socket.io') . '#/#';
     $this->_rooms = array();
     $this->_flags = array();
 }
Exemplo n.º 26
0
 function setup()
 {
     $redis = new Redis();
     $redis->connect(REDIS_HOST, REDIS_PORT);
     $redis->select(REDIS_DB);
     $this->redis = $redis;
 }
 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();
         }
     }
 }
Exemplo n.º 28
0
 /**
  * Initialize a Redis connection.
  * @TODO: support master/slave
  */
 protected static function connect($host, $port, $timeout = 1)
 {
     $redis = new \Redis();
     $redis->connect($host, $port, $timeout);
     //$redis->setOption(\Redis::OPT_READ_TIMEOUT, $timeout);
     return $redis;
 }
 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;
 }
Exemplo n.º 30
-1
 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']);
     }
 }