private function connect($server) { $redis = new Redis(); if ($redis->connect($server['host'], $server['port'], $server['timeout']) == false) { die($redis->getLastError()); } if (!empty($server['auth'])) { $auth = $server['auth']; if ($redis->auth($auth['user'] . ":" . $auth['password']) == false) { die($redis->getLastError()); } } return $redis; }
public function run($command, $args) { if (empty($this->sha)) { $this->reload(); } $luaArgs = [$command, microtime(true)]; $argArray = array_merge($luaArgs, $args); $result = $this->redisCli->evalSha($this->sha, $argArray); $error = $this->redisCli->getLastError(); if ($error) { $this->handleError($error); return null; } return $result; }
/** * Get cache element * * This method will throw only logical exceptions. * In case of failures, it will return a null value. * In case of cache not found, it will return a null value. * * @param string $name Name for cache element * * @return mixed * @throws \Comodojo\Exception\CacheException */ public function get($name) { if (empty($name)) { throw new CacheException("Name of object cannot be empty"); } if (!$this->isEnabled()) { return null; } $this->resetErrorState(); try { $namespace = $this->getNamespaceKey(); if ($namespace === false) { $return = false; } else { $shadowName = $namespace . "-" . md5($name); $return = $this->instance->get($shadowName); if ($return === false) { $this->raiseError("Error reading cache (PhpRedis), exiting gracefully", array($this->instance->getLastError())); $this->setErrorState(); } } } catch (CacheException $ce) { throw $ce; } catch (RedisException $re) { $this->raiseError("Server unreachable (PhpRedis), exiting gracefully", array("RESULTCODE" => $re->getCode(), "RESULTMESSAGE" => $re->getMessage())); $this->setErrorState(); return null; } return $return === false ? null : unserialize($return); }
public function testGetLastError() { // We shouldn't have any errors now $this->assertTrue($this->redis->getLastError() === NULL); // Throw some invalid lua at redis $this->redis->eval("not-a-lua-script"); // Now we should have an error $this->assertTrue(strlen($this->redis->getLastError()) > 0); }
public function testGetLastError() { // We shouldn't have any errors now $this->assertTrue($this->redis->getLastError() === NULL); // test getLastError with a regular command $this->redis->set('x', 'a'); $this->assertFalse($this->redis->incr('x')); $incrError = $this->redis->getLastError(); $this->assertTrue(strlen($incrError) > 0); // clear error $this->redis->clearLastError(); $this->assertTrue($this->redis->getLastError() === NULL); }
protected function mget() { $this->db->watch([$this->count]); $error = $this->db->getLastError(); if ($error) { return $error; } $replies = $this->db->mGet([$this->count, $this->limit, $this->reset]); $error = $this->db->getLastError(); if ($error) { return $error; } if (!$replies[0] && $replies[0] !== '0') { return $this->create(); } return $this->decr($replies); }
public function testGetLastError() { // We shouldn't have any errors now $this->assertTrue($this->redis->getLastError() === NULL); // Throw some invalid lua at redis $this->redis->eval("not-a-lua-script"); // Now we should have an error $evalError = $this->redis->getLastError(); $this->assertTrue(strlen($evalError) > 0); // test getLastError with a regular command $this->redis->set('x', 'a'); $this->assertFalse($this->redis->incr('x')); $incrError = $this->redis->getLastError(); $this->assertTrue($incrError !== $evalError); // error has changed $this->assertTrue(strlen($incrError) > 0); // clear error $this->redis->clearLastError(); $this->assertTrue($this->redis->getLastError() === NULL); }
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->IsConnected())) { $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; }
/** * @return string|NULL * */ public function getLastError() { return parent::getLastError(); }
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; } // Flatten arguments $argsFlat = null; foreach ($args as $index => $arg) { if (is_array($arg)) { if ($argsFlat === null) { $argsFlat = array_slice($args, 0, $index); } if ($name == 'mset' || $name == 'msetnx' || $name == 'hmset') { foreach ($arg as $key => $value) { $argsFlat[] = $key; $argsFlat[] = $value; } } else { $argsFlat = array_merge($argsFlat, $arg); } } elseif ($argsFlat !== null) { $argsFlat[] = $arg; } } if ($argsFlat !== null) { $args = $argsFlat; $argsFlat = null; } // In pipeline mode if ($this->usePipeline) { if ($name == 'pipeline') { throw new CredisException('A pipeline is already in use and only one pipeline is supported.'); } elseif ($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); // Watch mode disables reconnect so error is thrown if ($name == 'watch') { $this->isWatching = true; } elseif ($this->isMulti && ($name == 'exec' || $name == 'discard')) { $this->isMulti = false; } elseif ($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': 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; default: // Flatten arguments $argsFlat = null; foreach ($args as $index => $arg) { if (is_array($arg)) { if ($argsFlat === null) { $argsFlat = array_slice($args, 0, $index); } $argsFlat = array_merge($argsFlat, $arg); } elseif ($argsFlat !== null) { $argsFlat[] = $arg; } } if ($argsFlat !== null) { $args = $argsFlat; $argsFlat = null; } } 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); } } elseif ($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->IsConnected())) { $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; } elseif ($error) { throw new CredisException($error); } break; default: $error = $this->redis->getLastError(); $this->redis->clearLastError(); if ($error) { throw new CredisException($error); } break; } } return $response; }
$port = 6379; } elseif (App == "product") { $host = "172.17.16.46"; $port = 6379; $instanceid = "16fd0afe-7bfd-4f00-b546-5768a6b61995"; $pwd = "gc7232275"; } elseif (App == "test") { $host = "172.17.11.5"; $port = 6379; } else { exit("未知环境"); } $redis = new Redis(); //连接redis if ($redis->connect($host, $port) == false) { die($redis->getLastError()); } //鉴权 if (App == "product" && $redis->auth($instanceid . ":" . $pwd) == false) { die("鉴权验证失败!"); } $pinyinArr = json_decode(file_get_contents("/data/cap/V3/gc.api/branches/dev/vendor/xz/composerlib/XzFunc/data/dict.php")); foreach ($pinyinArr as $key => $value) { $checkArr = $redis->get("py:" . $key); if ($checkArr) { var_dump($checkArr); echo "\n"; echo App . "环境已经初始化过了!"; exit; } if ($redis->set("py:" . $key, $value) == false) {
<?php $redis = new Redis(); $redis->connect('127.0.0.1', 6300); if (file_exists('./merge_data.sha')) { $evalSha = file_get_contents('./merge_data.sha'); } if (empty($evalSha)) { $evalSha = $redis->script("load", file_get_contents('merge_data.lua')); file_put_contents('./merge_data.sha', $evalSha); } var_dump($redis->evalSha($evalSha), $redis->getLastError() ?: "No errors");
<?php // vim: set expandtab cindent tabstop=4 shiftwidth=4 fdm=marker: /** * @file redisEvalShaTest.php * @version 1.0 * @author wade * @date 2014-12-01 22:56:38 * @desc redis集成lua脚本功能实现浏览历史功能 */ $redis = new Redis(); $redis->connect('127.0.0.1', '6379'); // $redis->set('test', 'Hello World'); // echo $redis->get('test'); $luaScript = file_get_contents('./addItemToBrowsingHistory.lua'); $ret = $redis->eval($luaScript, array(4011, 'brand_browsing_10011', 1417582943, 'brand_expired_10011', 1417582943, 1417582943, 3, 1417482943)); var_export($ret); $err = $redis->getLastError(); var_export($err);
private function testRedis(\Redis $redis, $method, $params, $keyToCleanUp, OutputInterface $output) { if ($keyToCleanUp) { $redis->delete($keyToCleanUp); } $result = call_user_func_array(array($redis, $method), $params); $paramsInline = implode(', ', $params); if ($result) { $output->writeln("Success for method {$method}({$paramsInline})"); } else { $errorMessage = $redis->getLastError(); $output->writeln("<error>Failure for method {$method}({$paramsInline}): {$errorMessage}</error>"); } if ($keyToCleanUp) { $redis->delete($keyToCleanUp); } }
/** * @param mixed $result * * @throws QueueException */ protected function assertResult($result) { if (false === $result) { throw new QueueException($this, $this->redis->getLastError()); } }
function __construct() { $dbname = getC("BAE_FOR_MYKV_REDIS_NAME"); $host = getenv('HTTP_BAE_ENV_ADDR_REDIS_IP'); $port = getenv('HTTP_BAE_ENV_ADDR_REDIS_PORT'); $user = getenv('HTTP_BAE_ENV_AK'); $pwd = getenv('HTTP_BAE_ENV_SK'); try { $redis = new Redis(); $ret = $redis->connect($host, $port); if ($ret === false) { die($redis->getLastError()); } $ret = $redis->auth($user . "-" . $pwd . "-" . $dbname); if ($ret === false) { die($redis->getLastError()); } $this->redis = $redis; } catch (RedisException $e) { die("Uncaught exception " . $e->getMessage()); } }