/** * Stubbable method for setting timeouts on new keys * * @param array<\sndsgd\rate\LimitInterface> The limits to set timeouts for */ protected function setTimeouts(array $limits) { $pipe = $this->redis->multi(\Redis::PIPELINE); foreach ($limits as $limit) { $pipe->setTimeout($limit->getHash(), $limit->getDuration()); } $pipe->exec(); }
/** * 将批量数据加入队列开头 * @注意:当加入的数据量较大,比如超过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; }
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; }
/** * Disable a dark launch feature * @param $feature string - The name of the feature */ public function disable_feature($feature_name) { $multi = $this->redis->multi(); $this->redis->del("{$this->feature_namespace()}:feature:{$feature_name}"); $this->redis->srem("{$this->feature_namespace()}:features", $feature_name); $multi->exec(); }
/** * Helper method for flushByTag() * Gets list of identifiers and tags and removes all relations of those tags * * Scales O(1) with number of cache entries * Scales O(n^2) with number of tags * * @param array $identifiers List of identifiers to remove * @param array $tags List of tags to be handled * @return void */ protected function removeIdentifierEntriesAndRelations(array $identifiers, array $tags) { // Set a temporary entry which holds all identifiers that need to be removed from // the tag to identifiers sets $uniqueTempKey = 'temp:' . uniqid('', TRUE); $prefixedKeysToDelete = array($uniqueTempKey); $prefixedIdentifierToTagsKeysToDelete = array(); foreach ($identifiers as $identifier) { $prefixedKeysToDelete[] = self::IDENTIFIER_DATA_PREFIX . $identifier; $prefixedIdentifierToTagsKeysToDelete[] = self::IDENTIFIER_TAGS_PREFIX . $identifier; } foreach ($tags as $tag) { $prefixedKeysToDelete[] = self::TAG_IDENTIFIERS_PREFIX . $tag; } $tagToIdentifiersSetsToRemoveIdentifiersFrom = $this->redis->sUnion($prefixedIdentifierToTagsKeysToDelete); // Remove the tag to identifier set of the given tags, they will be removed anyway $tagToIdentifiersSetsToRemoveIdentifiersFrom = array_diff($tagToIdentifiersSetsToRemoveIdentifiersFrom, $tags); // Diff all identifiers that must be removed from tag to identifiers sets off from a // tag to identifiers set and store result in same tag to identifiers set again $queue = $this->redis->multi(\Redis::PIPELINE); foreach ($identifiers as $identifier) { $queue->sAdd($uniqueTempKey, $identifier); } foreach ($tagToIdentifiersSetsToRemoveIdentifiersFrom as $tagToIdentifiersSet) { $queue->sDiffStore(self::TAG_IDENTIFIERS_PREFIX . $tagToIdentifiersSet, self::TAG_IDENTIFIERS_PREFIX . $tagToIdentifiersSet, $uniqueTempKey); } $queue->delete(array_merge($prefixedKeysToDelete, $prefixedIdentifierToTagsKeysToDelete)); $queue->exec(); }
/** * @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; }
/** * 开启事务 */ public function multi() { try { return $this->_redis->multi(Redis::MULTI); } catch (Exception $e) { $this->_error = $e->getMessage(); return false; } }
/** * @param string $key * @return \Redis */ protected function multi($key) { if ($this->redis instanceof \RedisArray) { $host = $this->redis->_target($key); return $this->redis->multi($host); } return $this->redis->multi(); }
/** * Disable a dark launch feature * @param $feature string - The name of the feature */ public function disable_feature($feature_name) { $feature_name = str_replace('_', '-', $feature_name); $multi = $this->redis->multi(); $this->redis->hdel("{$this->_feature_namespace()}:feature", $feature_name); $this->redis->srem("{$this->_feature_namespace()}:features", $feature_name); $multi->exec(); }
/** * {@inheritdoc} */ public function close() { if ($this->redis instanceof \Redis) { $multi = $this->redis->multi(); foreach ($this->buffer as $record) { $multi->rpush($this->key, $record); } $multi->exec(); } else { $key =& $this->key; $buffer =& $this->buffer; $this->redis->multiExec(function ($multi) use($key, $buffer) { foreach ($buffer as $record) { $multi->rpush($key, $record); } }); } }
/** * @param string $key * * @return ProvidesKeyInformation */ public function getKeyInfoObject($key) { list($type, $ttl) = $this->redis->multi()->type($key)->pttl($key)->exec(); if ($type == \Redis::REDIS_HASH) { $subItems = $this->redis->hKeys($key); } else { $subItems = []; } return new KeyInfo($key, $type, $ttl, $subItems); }
/** * 批量删除Redis Key * * @param array $keys 键数组 */ public function deleteKeys($keys) { if (empty($keys)) { return false; } $pipeLine = $this->connect->multi(); foreach ($keys as $key) { $pipeLine->del($key); } $pipeLine->exec(); return true; }
public function defer($name, $params = array(), $callback = null) { if ($this->_redis === null) { $this->_connect(); } if (empty($this->_queue)) { $this->_redis->multi(\Redis::PIPELINE); } $this->_queue[] = array('callback' => $callback, 'params' => $params); if ($this->_profiler) { $this->_profiler->log($name, $params); } return call_user_func_array(array($this->_redis, $name), $params); }
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; }
/** * Send a message to the queue * * @param mixed $message Message to send to the active queue * @return string|null job id */ public function send($message) { try { $encodedMessage = serialize($message); } catch (Exception $e) { Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " failed to serialize message: '{$message}'"); Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " exception message: " . $e->getMessage()); Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " exception stacktrace: " . $e->getTraceAsString()); return null; } $jobId = Tinebase_Record_Abstract::generateUID(); $data = array('data' => $encodedMessage, 'sha1' => sha1($encodedMessage), 'time' => date_create()->format(Tinebase_Record_Abstract::ISO8601LONG), 'retry' => 0, 'status' => 'inQueue'); // run in transaction /** @noinspection PhpInternalEntityUsedInspection */ /** @noinspection PhpUndefinedMethodInspection */ $this->_redis->multi()->hMset($this->_dataStructName . ':' . $jobId, $data)->lPush($this->_queueStructName, $jobId)->exec(); return $jobId; }
/** * Places an email into our email queue, to be sent later (normally within a second or so). * @param array $email * @param string $priority an unsigned integer as a string, between 0 and 10. Lower has higher priority, so 0 is highest priority. */ function queue_email($email, $priority = '9') { $redis = new Redis(); $host = '127.0.0.1'; $port = 6379; $redis_connected = $redis->pconnect($host, $port); echo "Redis Connected: {$redis_connected}\n"; if ($redis_connected) { $email_job = []; $email_job['priority.created'] = $priority . '.' . time(); $email_job['data'] = json_encode($email); // Increase job index $email_job_index = $redis->incr('mail_sender:email_job_index'); $email_job['job_id'] = $email_job_index; var_dump($email_job); // Insert job as an atomic transaction $redis->multi()->hMset("mail_sender:email_job:{$email_job_index}", $email_job)->zAdd("mail_sender:email_jobs", 0, $email_job_index)->exec(); } }
/** * Send a message to the queue * * @param mixed $message Message to send to the active queue * @return string job id */ public function send($message) { try { $encodedMessage = serialize($message); } catch (Exception $e) { if (Tinebase_Core::isLogLevel(Zend_Log::ERR)) { Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " failed to serialize message for action: '{$action}'"); } if (Tinebase_Core::isLogLevel(Zend_Log::ERR)) { Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " exception message: " . $e->getMessage()); } if (Tinebase_Core::isLogLevel(Zend_Log::ERR)) { Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " exception stacktrace: " . $e->getTraceAsString()); } return; } $jobId = Tinebase_Record_Abstract::generateUID(); $data = array('data' => $encodedMessage, 'sha1' => sha1($encodedMessage), 'time' => date_create()->format(Tinebase_Record_Abstract::ISO8601LONG), 'retry' => 0, 'status' => 'inQueue'); // run in transaction $this->_redis->multi()->hMset($this->_dataStructName . ':' . $jobId, $data)->lPush($this->_queueStructName, $jobId)->exec(); return $jobId; }
protected function decr($res) { $n = ~~$res[0]; $max = ~~$res[1]; $ex = ~~$res[2]; $done = function () use(&$max, &$n, &$ex) { return ['total' => $max, 'remaining' => $n < 0 ? 0 : $n, 'reset' => $ex]; }; if ($n <= 0) { return $done(); } // $date_now = round(microtime(true) * 1000); // pexpire 有问题,不能用 $date_now = time(); $replies = $this->db->multi()->set($this->count, $n - 1, ['xx', 'ex' => $ex - $date_now])->expire($this->limit, $ex - $date_now)->expire($this->reset, $ex - $date_now)->exec(); $error = $this->db->getLastError(); if ($error) { return $error; } if (self::isFirstReplyNull($replies)) { return $this->mget(); } return $done(); }
/** * 使redis开启PIPELINE模式,命令最终通过exec才会确定执行 * @注意:pipeline能减少网络往来次数,提高效率,对于若干个写命令,可以开启此模式,最后exec执行 * @return \Redis对象 */ public function pipeline() { return $this->rd->multi(\Redis::PIPELINE); }
protected function releaseLock() { $this->redis->multi()->del('lock')->lPush('lock', 1)->exec(); }
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]); } } }
<?php $redis = new Redis(); $redis->connect('10.1.132.86', 6379); $pipe = $redis->multi(Redis::PIPELINE); for ($i = 0; $i < 10000; $i++) { $pipe->set("key::{$i}", str_pad($i, 4, '0', 0)); $pipe->get("key::{$i}"); } $replies = $pipe->exec(); echo "\n"; print_r($replies);
<?php /** * Created by PhpStorm. * User: xiehaowei * Date: 16/7/14 * Time: 下午4:25 */ $redis = new Redis(); $redis->multi();
public function beginTransaction() { $this->client->multi(\Redis::PIPELINE); }
/** * 清空Redis队列 * * @param string $queue Redis队列名 * * @return array 队列条目 */ public function clear($queue) { $result = $this->redis->multi()->lPop($queue)->rPop($queue)->del($queue)->exec(); return array('new' => $result[0], 'old' => $result[1]); }
$key = isset($_POST['key']) ? $_POST['key'] : ''; $script = isset($_POST['script']) ? $_POST['script'] : ''; $startTime = isset($_POST['startTime']) ? $_POST['startTime'] : time(); $runTime = isset($_POST['runTime']) ? $_POST['runTime'] : 0; $clientIp = isset($_POST['clientIp']) ? $_POST['clientIp'] : '0.0.0.0'; $remoteIp = $_SERVER['REMOTE_ADDR']; if (empty($data) || empty($id) || empty($pid) || empty($key)) { exit('error'); } $host = '172.16.53.68'; $port = 6381; $length = 50000; $rkey = $key; $rdata = serialize(array('id' => $id, 'time' => $startTime, 'runTime' => $runTime, 'clientIp' => $clientIp, 'remoteIp' => $remoteIp, 'script' => $script)); $rd = new Redis(); $rd->connect($host, $port); $r = $rd->multi()->lpush($rkey, $rdata)->ltrim($rkey, 0, $length - 1)->exec(); var_dump($r); $mcServers = '127.0.0.1:7600'; $mcd = new Memcached(); // 一致性hash $mcd->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT); $mcd->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); $mcd->setOption(Memcached::OPT_COMPRESSION, true); $serverArr = explode(' ', $mcServers); foreach ($serverArr as $k => $v) { $serverArr[$k] = explode(':', $v); } $mcd->addServers($serverArr); $r = $mcd->set($id, $data, 86400 * 14); var_dump($r);
protected function sequence($mode) { $ret = $this->redis->multi($mode)->set('x', 42)->info()->type('x')->get('x')->exec(); $this->assertTrue(is_array($ret)); $i = 0; $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue(is_array($ret[$i++])); $this->assertTrue($ret[$i++] === Redis::REDIS_STRING); $this->assertTrue($ret[$i] === '42' || $ret[$i] === 42); $serializer = $this->redis->getOption(Redis::OPT_SERIALIZER); $this->redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // testing incr, which doesn't work with the serializer $ret = $this->redis->multi($mode)->delete('key1')->set('key1', 'value1')->get('key1')->getSet('key1', 'value2')->get('key1')->set('key2', 4)->incr('key2')->get('key2')->decr('key2')->get('key2')->renameKey('key2', 'key3')->get('key3')->renameNx('key3', 'key1')->renameKey('key3', 'key2')->incr('key2', 5)->get('key2')->decr('key2', 5)->get('key2')->exec(); $this->assertTrue(is_array($ret)); $i = 0; $this->assertTrue(is_long($ret[$i++])); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 'value1'); $this->assertTrue($ret[$i++] == 'value1'); $this->assertTrue($ret[$i++] == 'value2'); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 5); $this->assertTrue($ret[$i++] == 5); $this->assertTrue($ret[$i++] == 4); $this->assertTrue($ret[$i++] == 4); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 4); $this->assertTrue($ret[$i++] == FALSE); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 9); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 4); $this->assertTrue(count($ret) == $i); $this->redis->setOption(Redis::OPT_SERIALIZER, $serializer); $ret = $this->redis->multi($mode)->delete('key1')->delete('key2')->set('key1', 'val1')->setnx('key1', 'valX')->setnx('key2', 'valX')->exists('key1')->exists('key3')->ping()->exec(); $this->assertTrue(is_array($ret)); $this->assertTrue($ret[0] == TRUE); $this->assertTrue($ret[1] == TRUE); $this->assertTrue($ret[2] == TRUE); $this->assertTrue($ret[3] == FALSE); $this->assertTrue($ret[4] == TRUE); $this->assertTrue($ret[5] == TRUE); $this->assertTrue($ret[6] == FALSE); $this->assertTrue($ret[7] == '+PONG'); $ret = $this->redis->multi($mode)->randomKey()->exec(); $ret = $this->redis->multi($mode)->exec(); $this->assertTrue($ret == array()); // ttl, mget, mset, msetnx, expire, expireAt $this->redis->delete('key'); $ret = $this->redis->multi($mode)->ttl('key')->mget(array('key1', 'key2', 'key3'))->mset(array('key3' => 'value3', 'key4' => 'value4'))->set('key', 'value')->expire('key', 5)->ttl('key')->expireAt('key', '0000')->exec(); $this->assertTrue(is_array($ret)); $i = 0; $this->assertTrue($ret[$i++] == -1); $this->assertTrue($ret[$i++] === array('val1', 'valX', FALSE)); // mget $this->assertTrue($ret[$i++] === TRUE); // mset $this->assertTrue($ret[$i++] === TRUE); // set $this->assertTrue($ret[$i++] === TRUE); // expire $this->assertTrue($ret[$i++] === 5); // ttl $this->assertTrue($ret[$i++] === TRUE); // expireAt $this->assertTrue(count($ret) == $i); $ret = $this->redis->multi($mode)->set('lkey', 'x')->set('lDest', 'y')->delete('lkey', 'lDest')->rpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->rpoplpush('lkey', 'lDest')->lGetRange('lDest', 0, -1)->lpop('lkey')->llen('lkey')->lRemove('lkey', 'lvalue', 3)->llen('lkey')->lget('lkey', 0)->lGetRange('lkey', 0, -1)->lSet('lkey', 1, "newValue")->lGetRange('lkey', 0, -1)->llen('lkey')->exec(); $this->assertTrue(is_array($ret)); $i = 0; $this->assertTrue($ret[$i++] === TRUE); // SET $this->assertTrue($ret[$i++] === TRUE); // SET $this->assertTrue($ret[$i++] === 2); // deleting 2 keys $this->assertTrue($ret[$i++] === 1); // rpush, now 1 element $this->assertTrue($ret[$i++] === 2); // lpush, now 2 elements $this->assertTrue($ret[$i++] === 3); // lpush, now 3 elements $this->assertTrue($ret[$i++] === 4); // lpush, now 4 elements $this->assertTrue($ret[$i++] === 5); // lpush, now 5 elements $this->assertTrue($ret[$i++] === 6); // lpush, now 6 elements $this->assertTrue($ret[$i++] === 'lvalue'); // rpoplpush returns the element: "lvalue" $this->assertTrue($ret[$i++] === array('lvalue')); // lDest contains only that one element. $this->assertTrue($ret[$i++] === 'lvalue'); // removing a second element from lkey, now 4 elements left ↓ $this->assertTrue($ret[$i++] === 4); // 4 elements left, after 2 pops. $this->assertTrue($ret[$i++] === 3); // removing 3 elements, now 1 left. $this->assertTrue($ret[$i++] === 1); // 1 element left $this->assertTrue($ret[$i++] === "lvalue"); // this is the current head. $this->assertTrue($ret[$i++] === array("lvalue")); // this is the current list. $this->assertTrue($ret[$i++] === FALSE); // updating a non-existent element fails. $this->assertTrue($ret[$i++] === array("lvalue")); // this is the current list. $this->assertTrue($ret[$i++] === 1); // 1 element left $this->assertTrue(count($ret) == $i); $ret = $this->redis->multi(Redis::PIPELINE)->delete('lkey', 'lDest')->rpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->rpoplpush('lkey', 'lDest')->lGetRange('lDest', 0, -1)->lpop('lkey')->exec(); $this->assertTrue(is_array($ret)); $i = 0; $this->assertTrue($ret[$i++] <= 2); // deleted 0, 1, or 2 items $this->assertTrue($ret[$i++] === 1); // 1 element in the list $this->assertTrue($ret[$i++] === 2); // 2 elements in the list $this->assertTrue($ret[$i++] === 3); // 3 elements in the list $this->assertTrue($ret[$i++] === 'lvalue'); // rpoplpush returns the element: "lvalue" $this->assertTrue($ret[$i++] === array('lvalue')); // rpoplpush returns the element: "lvalue" $this->assertTrue($ret[$i++] === 'lvalue'); // pop returns the front element: "lvalue" $this->assertTrue(count($ret) == $i); // general command $ret = $this->redis->multi($mode)->select(3)->set('keyAAA', 'value')->set('keyAAB', 'value')->dbSize()->lastsave()->exec(); $this->redis->select(0); // back to normal $i = 0; $this->assertTrue(is_array($ret)); $this->assertTrue($ret[$i++] === TRUE); // select $this->assertTrue($ret[$i++] === TRUE); // set $this->assertTrue($ret[$i++] === TRUE); // set $this->assertTrue(is_long($ret[$i++])); // dbsize $this->assertTrue(is_long($ret[$i++])); // lastsave $this->assertTrue(count($ret) === $i); $serializer = $this->redis->getOption(Redis::OPT_SERIALIZER); $this->redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // testing incr, which doesn't work with the serializer $ret = $this->redis->multi($mode)->delete('key1')->set('key1', 'value1')->get('key1')->getSet('key1', 'value2')->get('key1')->set('key2', 4)->incr('key2')->get('key2')->decr('key2')->get('key2')->renameKey('key2', 'key3')->get('key3')->renameNx('key3', 'key1')->renameKey('key3', 'key2')->incr('key2', 5)->get('key2')->decr('key2', 5)->get('key2')->exec(); $i = 0; $this->assertTrue(is_array($ret)); $this->assertTrue(is_long($ret[$i]) && $ret[$i] <= 1); $i++; $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 'value1'); $this->assertTrue($ret[$i++] == 'value1'); $this->assertTrue($ret[$i++] == 'value2'); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 5); $this->assertTrue($ret[$i++] == 5); $this->assertTrue($ret[$i++] == 4); $this->assertTrue($ret[$i++] == 4); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 4); $this->assertTrue($ret[$i++] == FALSE); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 9); $this->assertTrue($ret[$i++] == TRUE); $this->assertTrue($ret[$i++] == 4); $this->redis->setOption(Redis::OPT_SERIALIZER, $serializer); $ret = $this->redis->multi($mode)->delete('key1')->delete('key2')->set('key1', 'val1')->setnx('key1', 'valX')->setnx('key2', 'valX')->exists('key1')->exists('key3')->ping()->exec(); $this->assertTrue(is_array($ret)); $this->assertTrue($ret[0] == TRUE); $this->assertTrue($ret[1] == TRUE); $this->assertTrue($ret[2] == TRUE); $this->assertTrue($ret[3] == FALSE); $this->assertTrue($ret[4] == TRUE); $this->assertTrue($ret[5] == TRUE); $this->assertTrue($ret[6] == FALSE); $this->assertTrue($ret[7] == '+PONG'); $ret = $this->redis->multi($mode)->randomKey()->exec(); $this->assertTrue(is_array($ret) && count($ret) === 1); $this->assertTrue(is_string($ret[0])); // ttl, mget, mset, msetnx, expire, expireAt $ret = $this->redis->multi($mode)->ttl('key')->mget(array('key1', 'key2', 'key3'))->mset(array('key3' => 'value3', 'key4' => 'value4'))->set('key', 'value')->expire('key', 5)->ttl('key')->expireAt('key', '0000')->exec(); $i = 0; $this->assertTrue(is_array($ret)); $this->assertTrue(is_long($ret[$i++])); $this->assertTrue(is_array($ret[$i]) && count($ret[$i]) === 3); // mget $i++; $this->assertTrue($ret[$i++] === TRUE); // mset always returns TRUE $this->assertTrue($ret[$i++] === TRUE); // set always returns TRUE $this->assertTrue($ret[$i++] === TRUE); // expire always returns TRUE $this->assertTrue($ret[$i++] === 5); // TTL was just set. $this->assertTrue($ret[$i++] === TRUE); // expireAt returns TRUE for an existing key $this->assertTrue(count($ret) === $i); // lists $ret = $this->redis->multi($mode)->delete('lkey', 'lDest')->rpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->lpush('lkey', 'lvalue')->rpoplpush('lkey', 'lDest')->lGetRange('lDest', 0, -1)->lpop('lkey')->llen('lkey')->lRemove('lkey', 'lvalue', 3)->llen('lkey')->lget('lkey', 0)->lGetRange('lkey', 0, -1)->lSet('lkey', 1, "newValue")->lGetRange('lkey', 0, -1)->llen('lkey')->exec(); $this->assertTrue(is_array($ret)); $i = 0; $this->assertTrue($ret[$i] >= 0 && $ret[$i] <= 2); // delete $i++; $this->assertTrue($ret[$i++] === 1); // 1 value $this->assertTrue($ret[$i++] === 2); // 2 values $this->assertTrue($ret[$i++] === 3); // 3 values $this->assertTrue($ret[$i++] === 4); // 4 values $this->assertTrue($ret[$i++] === 5); // 5 values $this->assertTrue($ret[$i++] === 6); // 6 values $this->assertTrue($ret[$i++] === 'lvalue'); $this->assertTrue($ret[$i++] === array('lvalue')); // 1 value only in lDest $this->assertTrue($ret[$i++] === 'lvalue'); // now 4 values left $this->assertTrue($ret[$i++] === 4); $this->assertTrue($ret[$i++] === 3); // removing 3 elements. $this->assertTrue($ret[$i++] === 1); // length is now 1 $this->assertTrue($ret[$i++] === 'lvalue'); // this is the head $this->assertTrue($ret[$i++] === array('lvalue')); // 1 value only in lkey $this->assertTrue($ret[$i++] === FALSE); // can't set list[1] if we only have a single value in it. $this->assertTrue($ret[$i++] === array('lvalue')); // the previous error didn't touch anything. $this->assertTrue($ret[$i++] === 1); // the previous error didn't change the length $this->assertTrue(count($ret) === $i); // sets $ret = $this->redis->multi($mode)->delete('skey1', 'skey2', 'skeydest', 'skeyUnion', 'sDiffDest')->sadd('skey1', 'sValue1')->sadd('skey1', 'sValue2')->sadd('skey1', 'sValue3')->sadd('skey1', 'sValue4')->sadd('skey2', 'sValue1')->sadd('skey2', 'sValue2')->sSize('skey1')->sRemove('skey1', 'sValue2')->sSize('skey1')->sMove('skey1', 'skey2', 'sValue4')->sSize('skey2')->sContains('skey2', 'sValue4')->sMembers('skey1')->sMembers('skey2')->sInter('skey1', 'skey2')->sInterStore('skeydest', 'skey1', 'skey2')->sMembers('skeydest')->sUnion('skey2', 'skeydest')->sUnionStore('skeyUnion', 'skey2', 'skeydest')->sMembers('skeyUnion')->sDiff('skey1', 'skey2')->sDiffStore('sDiffDest', 'skey1', 'skey2')->sMembers('sDiffDest')->sPop('skey2')->sSize('skey2')->exec(); $i = 0; $this->assertTrue(is_array($ret)); $this->assertTrue(is_long($ret[$i]) && $ret[$i] >= 0 && $ret[$i] <= 5); $i++; // deleted at most 5 values. $this->assertTrue($ret[$i++] === 1); // skey1 now has 1 element. $this->assertTrue($ret[$i++] === 1); // skey1 now has 2 elements. $this->assertTrue($ret[$i++] === 1); // skey1 now has 3 elements. $this->assertTrue($ret[$i++] === 1); // skey1 now has 4 elements. $this->assertTrue($ret[$i++] === 1); // skey2 now has 1 element. $this->assertTrue($ret[$i++] === 1); // skey2 now has 2 elements. $this->assertTrue($ret[$i++] === 4); $this->assertTrue($ret[$i++] === 1); // we did remove that value. $this->assertTrue($ret[$i++] === 3); // now 3 values only. $this->assertTrue($ret[$i++] === TRUE); // the move did succeed. $this->assertTrue($ret[$i++] === 3); // sKey2 now has 3 values. $this->assertTrue($ret[$i++] === TRUE); // sKey2 does contain sValue4. foreach (array('sValue1', 'sValue3') as $k) { // sKey1 contains sValue1 and sValue3. $this->assertTrue(in_array($k, $ret[$i])); } $this->assertTrue(count($ret[$i++]) === 2); foreach (array('sValue1', 'sValue2', 'sValue4') as $k) { // sKey2 contains sValue1, sValue2, and sValue4. $this->assertTrue(in_array($k, $ret[$i])); } $this->assertTrue(count($ret[$i++]) === 3); $this->assertTrue($ret[$i++] === array('sValue1')); // intersection $this->assertTrue($ret[$i++] === 1); // intersection + store → 1 value in the destination set. $this->assertTrue($ret[$i++] === array('sValue1')); // sinterstore destination contents foreach (array('sValue1', 'sValue2', 'sValue4') as $k) { // (skeydest U sKey2) contains sValue1, sValue2, and sValue4. $this->assertTrue(in_array($k, $ret[$i])); } $this->assertTrue(count($ret[$i++]) === 3); // union size $this->assertTrue($ret[$i++] === 3); // unionstore size foreach (array('sValue1', 'sValue2', 'sValue4') as $k) { // (skeyUnion) contains sValue1, sValue2, and sValue4. $this->assertTrue(in_array($k, $ret[$i])); } $this->assertTrue(count($ret[$i++]) === 3); // skeyUnion size $this->assertTrue($ret[$i++] === array('sValue3')); // diff skey1, skey2 : only sValue3 is not shared. $this->assertTrue($ret[$i++] === 1); // sdiffstore size == 1 $this->assertTrue($ret[$i++] === array('sValue3')); // contents of sDiffDest $this->assertTrue(in_array($ret[$i++], array('sValue1', 'sValue2', 'sValue4'))); // we removed an element from sKey2 $this->assertTrue($ret[$i++] === 2); // sKey2 now has 2 elements only. $this->assertTrue(count($ret) === $i); // sorted sets $ret = $this->redis->multi($mode)->delete('zkey1', 'zkey2', 'zkey5')->zadd('zkey1', 1, 'zValue1')->zadd('zkey1', 5, 'zValue5')->zadd('zkey1', 2, 'zValue2')->zRange('zkey1', 0, -1)->zDelete('zkey1', 'zValue2')->zRange('zkey1', 0, -1)->zadd('zkey1', 11, 'zValue11')->zadd('zkey1', 12, 'zValue12')->zadd('zkey1', 13, 'zValue13')->zadd('zkey1', 14, 'zValue14')->zadd('zkey1', 15, 'zValue15')->zDeleteRangeByScore('zkey1', 11, 13)->zrange('zkey1', 0, -1)->zReverseRange('zkey1', 0, -1)->zRangeByScore('zkey1', 1, 6)->zCard('zkey1')->zScore('zkey1', 'zValue15')->zadd('zkey2', 5, 'zValue5')->zadd('zkey2', 2, 'zValue2')->zInter('zInter', array('zkey1', 'zkey2'))->zRange('zkey1', 0, -1)->zRange('zkey2', 0, -1)->zRange('zInter', 0, -1)->zUnion('zUnion', array('zkey1', 'zkey2'))->zRange('zUnion', 0, -1)->zadd('zkey5', 5, 'zValue5')->zIncrBy('zkey5', 3, 'zValue5')->zScore('zkey5', 'zValue5')->zScore('zkey5', 'unknown')->exec(); $i = 0; $this->assertTrue(is_array($ret)); $this->assertTrue(is_long($ret[$i]) && $ret[$i] >= 0 && $ret[$i] <= 3); $i++; // deleting at most 3 keys $this->assertTrue($ret[$i++] === 1); $this->assertTrue($ret[$i++] === 1); $this->assertTrue($ret[$i++] === 1); $this->assertTrue($ret[$i++] === array('zValue1', 'zValue2', 'zValue5')); $this->assertTrue($ret[$i++] === 1); $this->assertTrue($ret[$i++] === array('zValue1', 'zValue5')); $this->assertTrue($ret[$i++] === 1); // adding zValue11 $this->assertTrue($ret[$i++] === 1); // adding zValue12 $this->assertTrue($ret[$i++] === 1); // adding zValue13 $this->assertTrue($ret[$i++] === 1); // adding zValue14 $this->assertTrue($ret[$i++] === 1); // adding zValue15 $this->assertTrue($ret[$i++] === 3); // deleted zValue11, zValue12, zValue13 $this->assertTrue($ret[$i++] === array('zValue1', 'zValue5', 'zValue14', 'zValue15')); $this->assertTrue($ret[$i++] === array('zValue15', 'zValue14', 'zValue5', 'zValue1')); $this->assertTrue($ret[$i++] === array('zValue1', 'zValue5')); $this->assertTrue($ret[$i++] === 4); // 4 elements $this->assertTrue($ret[$i++] === 15.0); $this->assertTrue($ret[$i++] === 1); // added value $this->assertTrue($ret[$i++] === 1); // added value $this->assertTrue($ret[$i++] === 1); // zinter only has 1 value $this->assertTrue($ret[$i++] === array('zValue1', 'zValue5', 'zValue14', 'zValue15')); // zkey1 contents $this->assertTrue($ret[$i++] === array('zValue2', 'zValue5')); // zkey2 contents $this->assertTrue($ret[$i++] === array('zValue5')); // zinter contents $this->assertTrue($ret[$i++] === 5); // zUnion has 5 values (1,2,5,14,15) $this->assertTrue($ret[$i++] === array('zValue1', 'zValue2', 'zValue5', 'zValue14', 'zValue15')); // zunion contents $this->assertTrue($ret[$i++] === 1); // added value to zkey5, with score 5 $this->assertTrue($ret[$i++] === 8.0); // incremented score by 3 → it is now 8. $this->assertTrue($ret[$i++] === 8.0); // current score is 8. $this->assertTrue($ret[$i++] === FALSE); // score for unknown element. $this->assertTrue(count($ret) === $i); // hash $ret = $this->redis->multi($mode)->delete('hkey1')->hset('hkey1', 'key1', 'value1')->hset('hkey1', 'key2', 'value2')->hset('hkey1', 'key3', 'value3')->hmget('hkey1', array('key1', 'key2', 'key3'))->hget('hkey1', 'key1')->hlen('hkey1')->hdel('hkey1', 'key2')->hdel('hkey1', 'key2')->hexists('hkey1', 'key2')->hkeys('hkey1')->hvals('hkey1')->hgetall('hkey1')->hset('hkey1', 'valn', 1)->hset('hkey1', 'val-fail', 'non-string')->hget('hkey1', 'val-fail')->exec(); $i = 0; $this->assertTrue(is_array($ret)); $this->assertTrue($ret[$i++] <= 1); // delete $this->assertTrue($ret[$i++] === 1); // added 1 element $this->assertTrue($ret[$i++] === 1); // added 1 element $this->assertTrue($ret[$i++] === 1); // added 1 element $this->assertTrue($ret[$i++] === array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3')); // hmget, 3 elements $this->assertTrue($ret[$i++] === 'value1'); // hget $this->assertTrue($ret[$i++] === 3); // hlen $this->assertTrue($ret[$i++] === 1); // hdel succeeded $this->assertTrue($ret[$i++] === 0); // hdel failed $this->assertTrue($ret[$i++] === FALSE); // hexists didn't find the deleted key $this->assertTrue($ret[$i] === array('key1', 'key3') || $ret[$i] === array('key3', 'key1')); $i++; // hkeys $this->assertTrue($ret[$i] === array('value1', 'value3') || $ret[$i] === array('value3', 'value1')); $i++; // hvals $this->assertTrue($ret[$i] === array('key1' => 'value1', 'key3' => 'value3') || $ret[$i] === array('key3' => 'value3', 'key1' => 'value1')); $i++; // hgetall $this->assertTrue($ret[$i++] === 1); // added 1 element $this->assertTrue($ret[$i++] === 1); // added the element, so 1. $this->assertTrue($ret[$i++] === 'non-string'); // hset succeeded $this->assertTrue(count($ret) === $i); $ret = $this->redis->multi($mode)->delete('test')->set('test', 'xyz')->get('test')->exec(); $i = 0; $this->assertTrue(is_array($ret)); $this->assertTrue($ret[$i++] <= 1); // delete $this->assertTrue($ret[$i++] === TRUE); // added 1 element $this->assertTrue($ret[$i++] === 'xyz'); $this->assertTrue(count($ret) === $i); // GitHub issue 78 $this->redis->del('test'); for ($i = 1; $i <= 5; $i++) { $this->redis->zadd('test', $i, (string) $i); } $result = $this->redis->multi($mode)->zscore('test', "1")->zscore('test', "6")->zscore('test', "8")->zscore('test', "2")->exec(); $this->assertTrue($result === array(1.0, FALSE, FALSE, 2.0)); }
$redis->expire($key, 60); //使用秒为单位 $redis->pExpire($key, 60000); //使用毫秒作为单位 $redis->expireAt($key, 1476868380); //使用Unix timestamp,指定时间过期 $redis->pExpireAt($key, 1476868380000.0); //使用Unix timestamp在指定时间过期,区别是毫秒作为单位 $redis->persist($key); //移除给定key的生存时间 $redis->ttl($key); //返回key剩余的过期时间,使用秒为单位 $redis->pttl($key); //返回key剩余的过期时间,使用毫秒作为单位 $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;
/** * Remove and return all members of a set * * @param string $key * @return string[] */ public function sFlush($key) { $values = $this->_redis->multi()->sMembers($key)->delete($key)->exec(); return $values[0]; }