/** * 将批量数据加入队列开头 * @注意:当加入的数据量较大,比如超过10KB时,建议使用pipeline方式 * @注意:当提交的数据条数较多时,$pipeline为FALSE效率更高 * @param array $arrValues array('v1','v2') 按照数组的顺序,第一个元素将首先被加入队列,最后一个元素将最后加入队列 * @param bool $pipeline 默认为FALSE。当为TRUE时,通过PIPELINE的模式提交,为FALSE时,通过原生的方式提交。 * @return long 成功返回TRUE(可能是0),失败时返回FALSE */ public function pushMulti($arrValues, $pipeline = FALSE) { if ($pipeline) { if (!$this->rd->isConnected()) { if (!$this->reconnRedis()) { return FALSE; } } $this->rd->multi(\Redis::PIPELINE); foreach ($arrValues as $v) { $this->rd->lPush($this->k, $v); } $re = $this->rd->exec(); return TRUE; } else { array_unshift($arrValues, $this->k); try { return call_user_func_array(array($this->rd, 'lPush'), $arrValues); } catch (\RedisException $e) { if ($this->reconnRedis()) { return call_user_func_array(array($this->rd, 'lPush'), $arrValues); } } } return FALSE; }
/** * exec */ public function execs() { try { return $this->_redis->exec(); } catch (Exception $e) { $this->_error = $e->getMessage(); return false; } }
/** * @param string|int $taskId * @return bool */ public function isFinished($taskId) { $this->redis->multi(); $this->redis->hExists($this->getTaskKey(), $taskId); $this->redis->hExists($this->getTaskResultKey(), $taskId); list($taskExists, $taskResultExists) = $this->redis->exec(); return !$taskExists && $taskResultExists; }
/** * @param string $key * @param string $start * @param string $end * @param boolean|null $returnScore * @return array */ public function zPopRangeByScore($key, $start, $end, $returnScore = null) { $this->_redis->multi(); $this->zRangeByScore($key, $start, $end, null, null, $returnScore); $this->zRemRangeByScore($key, $start, $end); $result = $this->_redis->exec(); return $result[0]; }
private function requeueOldWorkingMessages($type) { $messageIds = array_unique($this->redis->lRange($this->getMessageRunKey($type), 0, -1)); foreach ($messageIds as $messageId) { $time = $this->redis->hGet($this->getMessageStartTimeKey($type), $messageId); if (!empty($time) && time() > $this->messageTimeout + (int) $time) { $this->redis->multi(); $this->redis->rPush($this->getMessageQueueKey($type), $messageId); $this->redis->lRem($this->getMessageRunKey($type), $messageId, 1); $this->redis->hDel($this->getMessageStartTimeKey($type), $messageId); $this->redis->exec(); } } }
/** * Freezes this cache backend. * * All data in a frozen backend remains unchanged and methods which try to add * or modify data result in an exception thrown. Possible expiry times of * individual cache entries are ignored. * * A frozen backend can only be thawn by calling the flush() method. * * @throws \RuntimeException * @return void */ public function freeze() { if ($this->isFrozen()) { throw new \RuntimeException(sprintf('Cannot add or modify cache entry because the backend of cache "%s" is frozen.', $this->cacheIdentifier), 1323344192); } do { $entriesKey = $this->buildKey('entries'); $this->redis->watch($entriesKey); $entries = $this->redis->lRange($entriesKey, 0, -1); $this->redis->multi(); foreach ($entries as $entryIdentifier) { $this->redis->persist($this->buildKey('entry:' . $entryIdentifier)); } $this->redis->set($this->buildKey('frozen'), 1); $result = $this->redis->exec(); } while ($result === false); $this->frozen = true; }
public function flush() { if (empty($this->_queue)) { return; } if ($this->_redis === null) { $this->_connect(); } if ($this->_profiler) { $this->_profiler->start(); } $results = $this->_redis->exec(); if ($this->_profiler) { $this->_profiler->execute(); } foreach ($this->_queue as $index => $command) { if (isset($command['callback'])) { $params = $command['params']; array_unshift($params, $results[$index]); call_user_func_array($command['callback'], $params); } } $this->_queue = array(); }
public function testEval() { if (version_compare($this->version, "2.5.0", "lt")) { $this->markTestSkipped(); } // Basic single line response tests $this->assertTrue(1 == $this->redis->eval('return 1')); $this->assertTrue(1.55 == $this->redis->eval("return '1.55'")); $this->assertTrue("hello, world" == $this->redis->eval("return 'hello, world'")); /* * Keys to be incorporated into lua results */ // Make a list $this->redis->del('mylist'); $this->redis->rpush('mylist', 'a'); $this->redis->rpush('mylist', 'b'); $this->redis->rpush('mylist', 'c'); // Make a set $this->redis->del('myset'); $this->redis->sadd('myset', 'd'); $this->redis->sadd('myset', 'e'); $this->redis->sadd('myset', 'f'); // Basic keys $this->redis->set('key1', 'hello, world'); $this->redis->set('key2', 'hello again!'); // Use a script to return our list, and verify its response $list = $this->redis->eval("return redis.call('lrange', 'mylist', 0, -1)"); $this->assertTrue($list === array('a', 'b', 'c')); // Use a script to return our set $set = $this->redis->eval("return redis.call('smembers', 'myset')"); $this->assertTrue($set == array('d', 'e', 'f')); // Test an empty MULTI BULK response $this->redis->del('not-any-kind-of-list'); $empty_resp = $this->redis->eval("return redis.call('lrange', 'not-any-kind-of-list', 0, -1)"); $this->assertTrue(is_array($empty_resp) && empty($empty_resp)); // Now test a nested reply $nested_script = "\n\t\t\treturn {\n\t\t\t\t1,2,3, {\n\t\t\t\t\tredis.call('get', 'key1'),\n\t\t\t\t\tredis.call('get', 'key2'),\n\t\t\t\t\tredis.call('lrange', 'not-any-kind-of-list', 0, -1),\n\t\t\t\t\t{\n\t\t\t\t\t\tredis.call('smembers','myset'),\n\t\t\t\t\t\tredis.call('lrange', 'mylist', 0, -1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t"; $expected = array(1, 2, 3, array('hello, world', 'hello again!', array(), array(array('d', 'e', 'f'), array('a', 'b', 'c')))); // Now run our script, and check our values against each other $eval_result = $this->redis->eval($nested_script); $this->assertTrue(is_array($eval_result) && count($this->array_diff_recursive($eval_result, $expected)) == 0); /* * Nested reply wihin a multi/pipeline block */ $num_scripts = 10; foreach (array(Redis::PIPELINE, Redis::MULTI) as $mode) { $this->redis->multi($mode); for ($i = 0; $i < $num_scripts; $i++) { $this->redis->eval($nested_script); } $replies = $this->redis->exec(); foreach ($replies as $reply) { $this->assertTrue(is_array($reply) && count($this->array_diff_recursive($reply, $expected)) == 0); } } /* * KEYS/ARGV */ $args_script = "return {KEYS[1],KEYS[2],KEYS[3],ARGV[1],ARGV[2],ARGV[3]}"; $args_args = array('k1', 'k2', 'k3', 'v1', 'v2', 'v3'); $args_result = $this->redis->eval($args_script, $args_args, 3); $this->assertTrue($args_result === $args_args); // turn on key prefixing $this->redis->setOption(Redis::OPT_PREFIX, 'prefix:'); $args_result = $this->redis->eval($args_script, $args_args, 3); // Make sure our first three are prefixed for ($i = 0; $i < count($args_result); $i++) { if ($i < 3) { // Should be prefixed $this->assertTrue($args_result[$i] == 'prefix:' . $args_args[$i]); } else { // Should not be prefixed $this->assertTrue($args_result[$i] == $args_args[$i]); } } }
/** * 写用户规则. * * @param array $matches_arr * @param string $hset_key */ protected function write_user_matches_rules($matches_arr = array(), $hset_key = "") { $this->load->config('redis'); $redis_config = $this->config->item('redis'); $redis = new Redis(); $redis->connect($redis_config['write']['hostname'], $redis_config['write']['port']); if (!empty($matches_arr)) { $redis->pipeline(); foreach ($matches_arr as $match_key => $matches_val) { sort($matches_val); $rules_redis_key = "DY_matches_rules:" . $match_key . ":"; $redis->hSet($rules_redis_key, $hset_key, json_encode($matches_val)); } $redis->exec(); } $redis->close(); }
/** * 执行Multi pipeline 命令,如果不执行,结果将不会存储 * @return array 每条命令执行的结果 $ret = array(0 => TRUE,1 => 'val1',2 => TRUE,3 => 'val2'); */ public function exec() { return $this->rd->exec(); }
/** * 提交完成事务 * bool $return 事务执行成功 提交操作 * @return Redis */ public function tranCommit() { return $this->_TRANSACTION->exec(); }
$redis->watch($key2); $ret = $redis->multi(Redis::MULTI)->get($key)->incr($key1)->del($key2)->exec(); $pip->incr('a'); $pip->get('test-num2'); $pip->incr('b'); $pip->del('a'); $ret = $pip->exec(); var_dump($ret); exit; $ret = $redis->incr('test-num2')->incr('test-num2')->exec(); exit('aa' . $redis->get('test-num2')); $redis->multi(Redis::PIPELINE); for ($i = 0; $i < 10000; $i++) { $redis->incr('test-num')->include('test-num2'); } $redis->exec(); exit; $it = null; $redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); while ($ret = $redis->scan($it, 'test*', 3)) { foreach ($ret as $item) { echo $item . PHP_EOL; } } exit; $key1 = 'key-list1'; $key2 = 'key-list2'; $timeout = 0; try { while ($item = $redis->brPop($key1, $key2, $timeout)) { var_dump($item);
public function commit() { return $this->client->exec(); }
<?php /* $dsn = "mysql:host=localhost;dbname=demo"; $db = new PDO($dsn, 'root', 'root'); */ $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->watch('myk'); $vn = $redis->get('myk'); $vn = $vn + 1; sleep(1); $redis->multi(); $redis->set('myk', $vn); $rs = $redis->exec(); if (!$rs) { error_log("eeee\n", 3, 'F:/logdata/eee.log'); }
$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());