public function testPing() { $this->assertEquals('+PONG', $this->redis->ping()); $count = 1000; while ($count--) { $this->assertEquals('+PONG', $this->redis->ping()); } }
public function isConnected() { try { $status = $this->redis->ping(); return $status == '+PONG'; } catch (RedisException $e) { return false; } }
/** * Check if we are still connected to the cache server, reconnect if not. * * @return bool */ private function ping() { if (!$this->connected) { return false; } switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: try { return (bool) $this->server->ping(); } catch (\RedisException $error) { // nothing to see here, move along } break; case self::TYPE_MEMCACHED: $versions = $this->server->getVersion(); if ($versions) { foreach ($versions as $version) { if ($version != "255.255.255") { return true; } } } break; case self::TYPE_APC: return true; default: return false; } $this->connect(); return $this->connected; }
/** * 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; }
private function __construct($config) { if ($config == 'REDIS_DEFAULT') { $conf['server'] = C('REDIS_HOST'); $conf['port'] = C('REDIS_PORT'); } else { $conf = C($config); } $this->redis = new Redis(); try { $this->redis->connect($conf['server'], $conf['port']); $this->redis->ping(); } catch (Exception $e) { throw_exception("RedisHandle_redis_connect 3 " . $e->getMessage()); } return $this->redis; }
/** * 查看redis连接是否断开 * @return $return bool true:连接未断开 false:连接已断开 */ public static function ping() { $redis = new \Redis(); $redis->connect(self::_HOST, self::_PORT); $return = null; $return = $redis->ping(); $redis->close(); $redis = null; return 'PONG' ? true : false; }
/** * Redis supports ping'ing the server, so use it. */ private function ping() { if ($this->isRedis === true) { try { return (bool) $this->server->ping(); } catch (\RedisException $error) { $this->connect(); return $this->connected; } } return true; }
/** * @param array $servers * @param string $prefix */ public function __construct($servers, $prefix = '') { $this->_redis = new Redis(); // setting default params if (!is_array($servers) || empty($servers)) { $servers = array(array('host' => 'localhost')); } foreach ($servers as $server) { $port = isset($server['port']) ? $server['port'] : 6379; $persist = isset($server['persist']) ? $server['persist'] : false; $timeout = isset($server['timeout']) ? $server['timeout'] : '2.5'; if ($persist) { $this->_redis->pconnect($server['host'], $port, $timeout); } else { $this->_redis->connect($server['host'], $port, $timeout); } } if ($this->_redis->ping() !== '+PONG') { throw new Exception('Unable to connect redis server.'); } $this->_prefix = $prefix; }
/** * Check if the Redis client connection is still up and reconnect if Redis was disconnected * * @return void * @throws JobQueueException */ protected function checkClientConnection() { $reconnect = false; try { $pong = $this->client->ping(); if ($pong === false) { $reconnect = true; } } catch (\RedisException $e) { $reconnect = true; } if ($reconnect) { if (!$this->connectClient()) { throw new JobQueueException('Could not connect to Redis', 1467382685); } } }
/** * 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; }
public function checkSlave() { $redis = new Redis(); $date = date('Y-m-d H:i:s'); $servers = $this->expansion_conf->getServers(); foreach ($servers as $s_v) { $_host = $s_v['host']; $_port = $s_v['port']; echo "[{$date}]Redis {$_host}:{$_port}'s dbsize is "; $available = $redis->connect($_host, $_port, 0.1); if (!$available || '+PONG' !== $redis->ping()) { echo "ERR"; } else { echo "[{$redis->dbsize()}]"; } echo "\n"; } }
public function _write_cache($output) { $CI =& get_instance(); $path = $CI->config->item('cache_path'); $cache_path = $path === '' ? APPPATH . 'cache/' : $path; $uri = $CI->config->item('base_url') . $CI->config->item('index_page') . $CI->uri->uri_string(); if ($CI->config->item('cache_query_string') && !empty($_SERVER['QUERY_STRING'])) { $uri .= '?' . $_SERVER['QUERY_STRING']; } $cache_path .= md5($uri); $redis = new Redis(); $host = $CI->config->item("redis_host"); $port = $CI->config->item("redis_port"); $redis->connect($host, $port); if (!$redis->ping()) { log_message('error', "Unable to ping to redis {$host}:{$port}"); return false; } if ($this->_compress_output === TRUE) { $output = gzencode($output); if ($this->get_header('content-type') === NULL) { $this->set_content_type($this->mime_type); } } $expire = time() + $this->cache_expiration; $cache_info = serialize(array('last_modified' => time(), 'expire' => $expire, 'headers' => $this->headers)); $output = $cache_info . 'ENDCI--->' . $output; try { $redis->set($cache_path, $output); $redis->expire($cache_path, $this->cache_expiration); $this->set_cache_header($_SERVER['REQUEST_TIME'], $expire); } catch (RedisException $e) { log_message('error', "Unable to set cache key"); return false; } }
preg_match_all('%<h[0-6]%', $new_rule_file, $headings); $toc_height = (count($headings[0]) ?: 0) * 30; $response->render('views/rules.php', array("rules" => $new_rule_file, "toc_height" => $toc_height)); }); respond('/changes/[i:old]/[i:member_id]/[*:view_key]', function ($request, $response) { $old = $request->param('old'); $member_id = $request->param('member_id', false); $view_key = substr($request->param('view_key', false), 7); $response->cookie('rule_set', $old); if ($member_id) { $response->cookie('rule_member_id', $member_id); if (is_numeric($member_id)) { $redis = new Redis(); $redis->connect(REDIS_IP, REDIS_PORT); $redis->auth(REDIS_AUTH); if (!$redis->ping()) { die('aw no redis :('); } $redis->lPush('users', json_encode(array("member_id" => $member_id, "time" => time(), "view_key" => $view_key))); } } $response->redirect('/', 301); }); respond('/compile/[*:secure_key]', function ($request, $response) { $secure_key = $request->param('secure_key', false); if ($secure_key != SECURE_KEY) { die('invalid secure key'); } $time = time(); $rule_sets = array_slice(scandir('rules'), 2); $all_rules = "<!-- compiled at " . $time . " -->" . "\n\n";
/** * 打开SESSION * * @param string $savePath SESSION保存的路径 * @param string $sessionName SESSION的KEY * * @return bool true/false */ public function open($savePath, $sessionName) { return $this->redis->ping(); }
<?php //连接本地的 Redis 服务 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully"; //查看服务是否运行 echo "<hr/>"; echo "Server is running: " . $redis->ping(); echo "<hr/>"; //Connection to server sucessfully //Server is running: PONG ############################################# //$redis->set('thename','heruyi'); //var_dump($redis->get('myname')); ############################################# //带生存时间的写入值 //$redis->setex('myname',20,'heruyi'); //var_dump($redis->get('myname')); ############################################# //hash key value //$redis->hset('office','oonane','yunachen'); //var_dump($redis->get('office')); ############################################## //delete //$redis->delete('thename') ################################################ //$redis->hset('tj','a',0); //$rs=$redis->hget('tj','a'); //var_dump($rs); /*$redis->hIncrBy('tj','a',1);
<?php $config = array('default' => array('host' => '172.17.163.80', 'port' => 8777, 'database' => 0)); $script_name = "index.php"; $server = isset($_GET["server"]) ? $_GET["server"] : 'default'; $db = isset($_GET["db"]) ? $_GET["db"] : 0; $action = isset($_GET["action"]) ? $_GET['action'] : 'list'; $pattern = isset($_GET['pattern']) ? $_GET['pattern'] : ''; $Redis = new Redis(); $Redis->connect($config[$server]['host'], $config[$server]['port'], 5); try { $Redis->ping(); } catch (Exception $e) { die("Couldn't connect to server [tcp://{$config[$server]['host']}:{$config[$server]['port']}]. " . $e->getMessage()); } $Redis->select($db); if (isset($_GET['key'])) { $Json = new Json($server, $db); $html = $Json->renderKey($Redis); exit(json_encode(array('html' => $html))); } $Html = new Html($server, $db); $Html->setScriptName($script_name); $Html->setAction($action); $Html->setPattern($pattern); $Html->setServerList($config); class Json { public function __construct($server, $db) { $this->server = $server;
error_reporting(E_ERROR); include_once 'inc/redis.php'; //конфигурация $config = array('host' => 'localhost', 'port' => 6379, 'db' => 0, 'db_name' => 'default'); //нам надо при старте сервера создать основные все переменные в памяти $item = array('users' => 'users_' . md5($config['db_name']), 'rooms' => 'rooms_' . md5($config['db_name']), 'admins' => 'admins_' . md5($config['db_name']), 'users_at_room' => '', 'msgs_at_room' => ''); //основной пользователь (админ) $_init_user = array('name' => 'admin', 'role' => 'admin', 'status' => 'online', 'password' => md5('qwerty'), 'at_chat' => date("d.m.Y H:i:s"), 'last_activity' => time()); $_first_msg = array('id' => 1, 'body' => 'Hello, its a first messages on this room: ', 'author' => $_init_user['name'], 'time' => date("H:i:s")); $srv = new Redis($config['host'], $config['port']); echo "Creating server object Redis \r\n\r\n"; //подключение $srv->connect(); echo "connecting to server... \r\n\r\n"; //пинг $srv->ping(); echo "Command: ping \r\n\r\n"; //очистка всего $srv->flishdb(); echo "Command: flush db \r\n\r\n"; //создаем список комнат $_rooms = array('default', 'moders', 'all'); //сохраним в переменной '_list_of_rooms' $srv->set('_list_of_rooms', serialize($_rooms)); echo "Setting up the room's list \r\n\r\n"; //создадим для всех комнат списки пустые foreach ($_rooms as $r) { $srv->push($r, $_init_user['name'], true); //добавляем сериализированный массив юзера в комнату echo "Room: " . $r . " - added user " . $_init_user['name'] . " \r\n\r\n"; //создаем пустые списки сообщений для каждой комнаты
} $result = mail(implode(',', $monitorsMail), '=?UTF-8?B?' . base64_encode("{$project['name']}的{$submodule['name']}({$submodule['code']})错误") . '?=', "详细错误:{$message},共{$mailMsgCount}次,来自{$onlineip}", $headers); //record msgCount to db $alarmMsg = array('pid' => $project['id'], 'mid' => $module['id'], 'sub_mid' => $submodule['id'], 'message' => $message, 'times' => $mailMsgCount, 'server_ip' => $onlineip, 'client_ip' => $client_ip, 'create_time' => $time); $keys = array_keys($alarmMsg); $keysStr = '`' . implode('`,`', $keys) . '`'; $values = array_values($alarmMsg); $valuesStr = '\'' . implode('\',\'', $values) . '\''; $insertSql = "INSERT INTO `message` ({$keysStr}) VALUES ({$valuesStr})"; $insertResult = mysqli_query($connMaster, $insertSql); memcache_delete($mc, $mailMsgKey); echo 'mail'; //exit('mail'); } } $xhprofId = isset($_GET['xhprof_id']) ? $_GET['xhprof_id'] : 0; $rd = new Redis(); $rd->connect($config['redis']['host'], $config['redis']['pass']); // $detail = date('[Y-m-d H:i:s] ', $time)."{$submodule['name']} 错误号:{$submodule['code']} 详细:{$message}, 邮件:第{$mailMsgCount}次,短信:第{$smsMsgCount}次,来自{$client_ip}/{$onlineip},xhprofId[{$xhprofId}]"; $detail = array('time' => $time, 'name' => $submodule['name'], 'code' => $submodule['code'], 'message' => $message, 'email' => $mailMsgCount, 'sms' => $smsMsgCount, 'serverIp' => $onlineip, 'clientIp' => $client_ip, 'script' => $script, 'xhprofId' => $xhprofId); $detail = serialize($detail); $times = 0; do { if ($rd->ping() !== '+PONG') { $rd->connect($config['redis'], $config['pass']); } $rd->multi()->lpush($submoduleKey, $detail)->ltrim($submoduleKey, 0, 5000)->lpush($projectKey, $detail)->ltrim($projectKey, 0, 5000)->hincrBy('allerr', $project['name'], 1)->hincrBy('allerr_detail', "{$project['name']}:{$submodule['id']}", 1); if (++$times > 3) { break; } } while (!$rd->exec());
/** * @inheritdoc */ public function check() { return extension_loaded('redis') && $this->driver->ping(); }
// 3. throw without catch class DivideByZeroException extends Exception { } //Throw new DivideByZeroException("DivideByZeroException1"); // 4. throw with exception handler // can NOT hook a exception_handler class ExceptionHandler { static $callback = array(); static function _exceptionHandler($e) { var_dump('ExceptionHandler'); call_user_func(self::$callback, $e); } } function exception_handler($exception) { var_dump('exception_handler', $exception->getTraceAsString(), 'exception_handler_end'); } set_exception_handler('ExceptionHandler::_exceptionHandler'); aop_add_before('set_exception_handler()', function ($jp) { $args = $jp->getArguments(); ExceptionHandler::$callback = $args[0]; $jp->setArguments(array('ExceptionHandler::_exceptionHandler')); }); set_exception_handler('exception_handler'); //Throw new DivideByZeroException("DivideByZeroException3"); $redis->connect('192.168.1.1', 6379, 1); $redis->ping();
/** * See if we can ping Redis server * * @param Redis $redis * @return bool */ protected function ping(Redis $redis) { try { if ($redis->ping() === false) { return false; } } catch (Exception $e) { return false; } return true; }
} } echo "<div id=\"topmain\" style=\"text-align:center;\">"; echo "*You can change the configuration at any time. Only the nodes given here, will be used to run VM."; echo "<form id=\"myform\" action=\"cluster.php?option=1\" method=\"post\">"; echo "<table align=center>"; echo "<tr><td>Number of Nodes:</td><td><input type=\"text\" name=\"number\"></td></tr><br>"; echo "<tr><td>IP of Nodes:</td><td><input type=\"text\" name=\"ip\" placeholder=\"IP-Address1,IP-Address2\"></td></tr><br>"; echo "</table>"; echo "<br>"; echo "<input type=\"Submit\" value=\"Add Nodes to Cluster\" name=\"submit\">"; echo "</form>"; echo "<hr>"; $redis = new Redis(); $redis->connect('127.0.0.1', 6379); if ($redis->ping()) { $num = $redis->get("cluster:num-nodes"); $res = null; for ($i = 0; $i < $num; $i++) { $ip = $redis->get("cluster:node" . $i); echo "<div id=\"widget\" style=\"float:left;font-size:100%;width:30%;margin-left:2.2%;\">"; echo "<div id=\"strip\">"; echo "NODE :" . $ip; echo "<button type=\"button\" class=\"primary\">-</button>"; echo "</div>"; echo "<div id=\"widget-main\">"; echo "<table style=\"font:serif;font-size:100%;text-align:left;\">"; $uri = "qemu+tcp://" . $ip . "/system"; $con = libvirt_connect($uri, false); if (!$con) { echo libvirt_get_last_error();
<?php /* $con = mysql_connect('localhost','root','abc123'); $db = mysql_select_db('test'); $q = "INSERT INTO notify ('user_id','msg') values ($user_id,$msg)"; mysql_query($q); */ $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo $redis->ping(); $redis->lPush("key1e", 1, 2, 3, 4); var_dump($redis->lRange('key1e', 0, -1)); $key = "Key_Name"; $redis->set($key, 'Key Value'); echo $redis->get($key); //echo $_POST['time'];
public function __call($name, $args) { // Lazy connection $this->connect(); $name = strtolower($name); // Send request via native PHP if ($this->standalone) { switch ($name) { case 'eval': case 'evalsha': $script = array_shift($args); $keys = (array) array_shift($args); $eArgs = (array) array_shift($args); $args = array($script, count($keys), $keys, $eArgs); break; case 'set': // The php redis module has different behaviour with ttl // https://github.com/phpredis/phpredis#set if (count($args) === 3 && is_int($args[2])) { $args = array($args[0], $args[1], array('EX', $args[2])); } elseif (count($args) === 3 && is_array($args[2])) { $tmp_args = $args; $args = array($tmp_args[0], $tmp_args[1]); foreach ($tmp_args[2] as $k => $v) { if (is_string($k)) { $args[] = array($k, $v); } elseif (is_int($k)) { $args[] = $v; } } unset($tmp_args); } break; case 'scan': case 'sscan': case 'hscan': case 'zscan': $ref =& $args[0]; if (empty($ref)) { $ref = 0; } $eArgs = array($ref); if (!empty($args[1])) { $eArgs[] = 'MATCH'; $eArgs[] = $args[1]; } if (!empty($args[2])) { $eArgs[] = 'COUNT'; $eArgs[] = $args[2]; } $args = $eArgs; break; case 'zrangebyscore': if (isset($args[3]) && is_array($args[3])) { // map options $cArgs = array(); if (!empty($args[3]['withscores'])) { $cArgs[] = 'withscores'; } if (array_key_exists('limit', $args[3])) { $cArgs[] = array('limit' => $args[3]['limit']); } $args[3] = $cArgs; } break; } // Flatten arguments $args = self::_flattenArguments($args); // In pipeline mode if ($this->usePipeline) { if ($name == 'pipeline') { throw new CredisException('A pipeline is already in use and only one pipeline is supported.'); } else { if ($name == 'exec') { if ($this->isMulti) { $this->commandNames[] = $name; $this->commands .= self::_prepare_command(array($this->getRenamedCommand($name))); } // Write request if ($this->commands) { $this->write_command($this->commands); } $this->commands = NULL; // Read response $response = array(); foreach ($this->commandNames as $command) { $response[] = $this->read_reply($command); } $this->commandNames = NULL; if ($this->isMulti) { $response = array_pop($response); } $this->usePipeline = $this->isMulti = FALSE; return $response; } else { if ($name == 'multi') { $this->isMulti = TRUE; } array_unshift($args, $this->getRenamedCommand($name)); $this->commandNames[] = $name; $this->commands .= self::_prepare_command($args); return $this; } } } // Start pipeline mode if ($name == 'pipeline') { $this->usePipeline = TRUE; $this->commandNames = array(); $this->commands = ''; return $this; } // If unwatching, allow reconnect with no error thrown if ($name == 'unwatch') { $this->isWatching = FALSE; } // Non-pipeline mode array_unshift($args, $this->getRenamedCommand($name)); $command = self::_prepare_command($args); $this->write_command($command); $response = $this->read_reply($name); switch ($name) { case 'scan': case 'sscan': case 'hscan': case 'zscan': $ref = array_shift($response); if (empty($ref)) { $response = false; } break; case 'zrangebyscore': if (in_array('withscores', $args, true)) { // Map array of values into key=>score list like phpRedis does $item = null; $out = array(); foreach ($response as $value) { if ($item == null) { $item = $value; } else { // 2nd value is the score $out[$item] = (double) $value; $item = null; } } $response = $out; } break; } // Watch mode disables reconnect so error is thrown if ($name == 'watch') { $this->isWatching = TRUE; } else { if ($this->isMulti && ($name == 'exec' || $name == 'discard')) { $this->isMulti = FALSE; } else { if ($this->isMulti || $name == 'multi') { $this->isMulti = TRUE; $response = $this; } } } } else { // Tweak arguments switch ($name) { case 'get': // optimize common cases // optimize common cases case 'set': case 'hget': case 'hset': case 'setex': case 'mset': case 'msetnx': case 'hmset': case 'hmget': case 'del': case 'zrangebyscore': break; case 'mget': if (isset($args[0]) && !is_array($args[0])) { $args = array($args); } break; case 'lrem': $args = array($args[0], $args[2], $args[1]); break; case 'eval': case 'evalsha': if (isset($args[1]) && is_array($args[1])) { $cKeys = $args[1]; } elseif (isset($args[1]) && is_string($args[1])) { $cKeys = array($args[1]); } else { $cKeys = array(); } if (isset($args[2]) && is_array($args[2])) { $cArgs = $args[2]; } elseif (isset($args[2]) && is_string($args[2])) { $cArgs = array($args[2]); } else { $cArgs = array(); } $args = array($args[0], array_merge($cKeys, $cArgs), count($cKeys)); break; case 'subscribe': case 'psubscribe': break; case 'scan': case 'sscan': case 'hscan': case 'zscan': // allow phpredis to see the caller's reference //$param_ref =& $args[0]; break; default: // Flatten arguments $args = self::_flattenArguments($args); } try { // Proxy pipeline mode to the phpredis library if ($name == 'pipeline' || $name == 'multi') { if ($this->isMulti) { return $this; } else { $this->isMulti = TRUE; $this->redisMulti = call_user_func_array(array($this->redis, $name), $args); } } else { if ($name == 'exec' || $name == 'discard') { $this->isMulti = FALSE; $response = $this->redisMulti->{$name}(); $this->redisMulti = NULL; #echo "> $name : ".substr(print_r($response, TRUE),0,100)."\n"; return $response; } } // Use aliases to be compatible with phpredis wrapper if (isset($this->wrapperMethods[$name])) { $name = $this->wrapperMethods[$name]; } // Multi and pipeline return self for chaining if ($this->isMulti) { call_user_func_array(array($this->redisMulti, $name), $args); return $this; } // Send request, retry one time when using persistent connections on the first request only $this->requests++; try { $response = call_user_func_array(array($this->redis, $name), $args); } catch (RedisException $e) { if ($this->persistent && $this->requests == 1 && $e->getMessage() == 'read error on connection') { $this->connected = FALSE; $this->connect(); $response = call_user_func_array(array($this->redis, $name), $args); } else { throw $e; } } } catch (RedisException $e) { $code = 0; if (!($result = $this->redis->ping())) { $this->connected = FALSE; $code = CredisException::CODE_DISCONNECTED; } throw new CredisException($e->getMessage(), $code, $e); } #echo "> $name : ".substr(print_r($response, TRUE),0,100)."\n"; // change return values where it is too difficult to minim in standalone mode switch ($name) { case 'hmget': $response = array_values($response); break; case 'type': $typeMap = array(self::TYPE_NONE, self::TYPE_STRING, self::TYPE_SET, self::TYPE_LIST, self::TYPE_ZSET, self::TYPE_HASH); $response = $typeMap[$response]; break; // Handle scripting errors // Handle scripting errors case 'eval': case 'evalsha': case 'script': $error = $this->redis->getLastError(); $this->redis->clearLastError(); if ($error && substr($error, 0, 8) == 'NOSCRIPT') { $response = NULL; } else { if ($error) { throw new CredisException($error); } } break; default: $error = $this->redis->getLastError(); $this->redis->clearLastError(); if ($error) { throw new CredisException($error); } break; } } return $response; }
public function testPing() { $this->assertEquals('+PONG', $this->redis->ping()); }
</table> </div> </div> <div class="row content"> <div class="col-md-6 col-md-offset-3 wrap"> <h2>Caching stuff</h2> <table class="table table-responsive table-striped table-hover"> <?php $redis = new Redis(); $redis->connect('127.0.0.1', 6379); ?> <tr> <td>Redis</td> <td><i class="fa fa-<?php echo $redis->ping() ? 'check' : 'times'; ?> "></i></td> </tr> <?php $memcached_running = FALSE; $memcached_version = FALSE; $memcached_version = FALSE; if (class_exists('Memcache')) { $m = new Memcached(); if ($m->addServer('localhost', 11211)) { $memcached_running = TRUE; $memcached_version = $m->getVersion(); $memcached_version = current($memcached_version); }
if (true === $commander->_i) { echo "Please specifing a kind of info to show.\n"; } else { if ($commander->_i) { $redis = new Redis(); $date = date('Y-m-d H:i:s'); $redis_servers = $redis_conf->getServers(); foreach ($redis_servers as $r_s_v) { $_host = $r_s_v['host']; $_port = $r_s_v['port']; if ($commander->_p && $_port != $commander->_p) { continue; } echo "[{$date}]Redis {$_host}:{$_port}'s "; $available = $redis->connect($_host, $_port, 0.5); if (!$available || '+PONG' !== $redis->ping()) { echo "ERR"; } else { switch ($commander->_i) { case 'dbsize': echo "dbsize: [{$redis->dbsize()}]"; break; case 'lastsave': echo 'lastsave: [' . date('Y-m-d H:i:s', $redis->lastSave()) . ']'; break; default: echo $commander->_i . ': ' . "\n"; foreach ($redis->info($commander->_i) as $i_k => $i_v) { echo "{$i_k}: {$i_v}\n"; } }