redis 通用函數php
construct 命令/方法/函數 Description Creates a Redis client 建立一個Redis客戶端 Example $redis = new Redis();
connect 命令/方法/函數
Description Connects to a Redis instance. 鏈接到一個Redis實例 Parameters
host: string. can be a host, or the path to a unix domain socket host:字符串類型 可使一個HOST IP或者是一個UNIX DOMAIN SOCKET的路徑 port: int, optional port:整數型,Redis的運行端口 timeout: float, value in seconds (optional, default is 0 meaning unlimited) timeout:浮點型,鏈接的市場,單位是秒,默認爲0即鏈接沒有時間限制 Return Value BOOL: TRUE on success, FALSE on error.
Example $redis->connect('127.0.0.1', 6379); $redis->connect('127.0.0.1'); // port 6379 by default $redis->connect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout. $redis->connect('/tmp/redis.sock'); // unix domain socket.
pconnect 命令/方法/函數 Description Connects to a Redis instance or reuse a connection already established with pconnect/popen. pconnect/popen用於鏈接一個Redis的實例或者複用一個已經存在的實例。 The connection will not be closed on close or end of request until the php process ends. So be patient on to many open FD's (specially on redis server side) when using persistent connections on many servers connecting to one redis server. 這個鏈接將不會被主動關閉,好比使用close(),或者PHP執行結束這個鏈接都不會被主動關閉。當有大量的connect請求在redis服務器端時,使用持久化的鏈接對象。 Also more than one persistent connection can be made identified by either host + port + timeout or host + persistent_id or unix socket + timeout. 一個持久化的鏈接實例,可使用HOST+PORT+TIMEOUT或者HOST+persistent_id或者SOCKET+TIMEOUT的方式建立。 This feature is not available in threaded versions. pconnect and popen then working like their non persistent equivalents. pconnect函數和popen函數在線程版本中不能被使用。 Parameters host: string. can be a host, or the path to a unix domain socket port: int, optional timeout: float, value in seconds (optional, default is 0 meaning unlimited) persistent_id: string. identity for the requested persistent connection Return Value BOOL: TRUE on success, FALSE on error. Example $redis->pconnect('127.0.0.1', 6379); $redis->pconnect('127.0.0.1'); // port 6379 by default - same connection like before. $redis->pconnect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout and would be another connection than the two before. $redis->pconnect('127.0.0.1', 6379, 2.5, 'x'); // x is sent as persistent_id and would be another connection the the three before. $redis->pconnect('/tmp/redis.sock'); // unix domain socket - would be another connection than the four before.
close 命令/方法/函數 Description Disconnects from the Redis instance, except when pconnect is used. 關閉Redis的鏈接實例,可是不能關閉用pconnect鏈接的實例 $redis->close();
setOption 命令/方法/函數 Description Set client option. 設置客戶端的選項 Parameters parameter name parameter value Return value BOOL: TRUE on success, FALSE on error. Example $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // don't serialize data $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); // use built-in serialize/unserialize $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // use igBinary serialize/unserialize $redis->setOption(Redis::OPT_PREFIX, 'myAppName:'); // use custom prefix on all keys
getOption 命令/方法/函數 Description Get client option. 取得客戶端的選項 Parameters parameter name Return value Parameter value. Example $redis->getOption(Redis::OPT_SERIALIZER); // return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, or Redis::SERIALIZER_IGBINARY.
ping 命令/方法/函數 Description Check the current connection status 檢查當前鏈接實例的狀態 Parameters (none) Return Value STRING: +PONG on success. Throws a RedisException object on connectivity error, as described above. 若是失敗,Throws一個RedisException對象報出鏈接錯誤。
echo 命令/方法/函數 Description Sends a string to Redis, which replies with the same string 發送一個字符串到Redis,返回一個相同的字符串 Parameters STRING: The message to send. Return Value STRING: the same message.
randomKey 命令/方法/函數 Description Returns a random key. 返回一個隨機的KEY。 Parameters None. Return value STRING: an existing key in redis. STRING:一個存在於REDIS中的KEY Example $key = $redis->randomKey(); $surprise = $redis->get($key); // who knows what's in there.
select 命令/方法/函數 Description Switches to a given database. 選擇數據庫。默認有16個數據庫,這個值能夠在redis.conf中配置。 Parameters INTEGER: dbindex, the database number to switch to. 整數值:數據庫索引,數據庫的ID Return value TRUE in case of success, FALSE in case of failure. 返回true表示成功,false表示失敗。
move 命令/方法/函數 Description Moves a key to a different database. 移動一個KEY-VALUE到另外一個DB Parameters Key: key, the key to move. key:要移動的key INTEGER: dbindex, the database number to move the key to. 整數值:要移動到的數據庫ID Return value BOOL: TRUE in case of success, FALSE in case of failure. 整數BOOL:返回true爲成功,返回false爲失敗。 Example $redis->select(0); // switch to DB 0 $redis->set('x', '42'); // write 42 to x $redis->move('x', 1); // move to DB 1 $redis->select(1); // switch to DB 1 $redis->get('x'); // will return 42
rename 命令/方法/函數 Description Renames a key. 重命名一個KEY Parameters STRING: srckey, the key to rename. STRING:源KEY,須要更名的KEY STRING: dstkey, the new name for the key. STRING:目標KEY,KEY的新名字 Return value BOOL: TRUE in case of success, FALSE in case of failure. Example $redis->set('x', '42'); $redis->rename('x', 'y'); $redis->get('y'); // → 42 $redis->get('x'); // → `FALSE`
renameNx 命令/方法/函數 Description Same as rename, but will not replace a key if the destination already exists. This is the same behaviour as setNx. 看起來功能和rename是同樣的,可是renameNx不是KEY更名的功能,而是複製一個KEY的VALUE到一個新的KEY。是複製出一個新的KEY-VALUE,而VALUE則是srcKEY的VALUE,而不是PHP中的引用概念。 Example $redis->set('x', '42'); $redis->renameNx('x', 'y'); $redis->get('y'); // → 42 $redis->get('x'); // → 42 $redis->set('x','39'); $redis->get('x'); //->39 $redis->get('y'); //->42
expire 命令/方法/函數 給KEY設置一個生存週期,單位爲秒。(pexpire相似,它是使用毫秒做爲計算單位) Parameters Key: key. The key that will disappear. Key:將被銷燬的KEY Integer: ttl. The key's remaining Time To Live, in seconds. integer:生命週期 Return value BOOL: TRUE in case of success, FALSE in case of failure. Example $redis->set('x', '42'); $redis->expire('x', 3); // x will disappear in 3 seconds. sleep(5); // wait 5 seconds $redis->get('x'); // will return `FALSE`, as 'x' has expired.
pexpire 命令/方法/函數 給KEY設置一個生存週期,單位爲毫秒。 Parameters Key:將被銷燬的KEY integer:生命週期 Return value BOOL: TRUE in case of success, FALSE in case of failure. Example $redis->set('x', 'php學習'); $redis->expire('x', 3000); // x will disappear in 3000 milliseconds. sleep(5); // wait 5 seconds $redis->get('x'); // will return `FALSE`, as 'x' has expired.
expireAt 命令/方法/函數 Description Sets an expiration date (a timestamp) on an item. pexpireAt requires a timestamp in milliseconds. 給一個KEY設置一個生命週期,單位是UNIX的時間戳。(pexpireAt與其相似,區別是單位爲毫秒) Parameters Key: key. The key that will disappear. Key:將被銷燬的key Integer: Unix timestamp. The key's date of death, in seconds from Epoch time. integer:Unix 時間戳 Return value BOOL: TRUE in case of success, FALSE in case of failure. Example $redis->set('x', '42'); $now = time(NULL); // current timestamp $redis->expireAt('x', $now + 3); // x will disappear in 3 seconds. sleep(5); // wait 5 seconds $redis->get('x'); // will return `FALSE`, as 'x' has expired.
pexpireAt 命令/方法/函數 Description 給一個KEY設置一個生命週期,單位爲毫秒。 Parameters Key: 將被銷燬的key integer: 過時時間(毫秒) Return value BOOL: TRUE in case of success, FALSE in case of failure. Example $redis->set('x', '42'); $now = time(); // current timestamp $redis->expireAt('x', $now + 3000); // x will disappear in 3000 milliseconds. sleep(5); // wait 5 seconds $redis->get('x'); // will return `FALSE`, as 'x' has expired.
keys 命令/方法/函數 Description Returns the keys that match a certain pattern. 返回某種計算模式取得的KEYS。 Parameters STRING: pattern, using '*' as a wildcard. STRING:計算符 Return value Array of STRING: The keys that match a certain pattern. Example $allKeys = $redis->keys('*'); // all keys will match this. 將會返回全部的key $keyWithUserPrefix = $redis->keys('user*'); //返回user打頭的key,至關於模糊搜索。 注意: 數據量較大的時候,慎用keys("*"),由於它會返回所有的key,會嚴重影響性能。
dbSize 命令/方法/函數 Description Returns the current database's size. 返回當前DB的KEY的數量,能夠查找當前有多少個key。 Parameters None. Return value INTEGER: DB size, in number of keys. 整型:DB的大小,key的數量。 Example $count = $redis->dbSize(); echo "Redis has $count keys\n";
auth 命令/方法/函數 Description Authenticate the connection using a password. Warning: The password is sent in plain-text over the network. 使用PASSWORD驗證連接。警告:PASSWD以明碼的形式在網絡中傳輸。 當redis配置了密碼認證的時候(去了解redis配置密碼的方法),須要經過此方法驗證受權。 Parameters STRING: password 字符串:密碼 Return value BOOL: TRUE if the connection is authenticated, FALSE otherwise. Example $redis->auth('foobared');
bgrewriteaof 命令/方法/函數 Description Starts the background rewrite of AOF (Append-Only File) 使用aof來進行數據庫持久化。 Parameters None. Return value BOOL: TRUE in case of success, FALSE in case of failure. Example $redis->bgrewriteaof();
slaveof 命令/方法/函數 Changes the slave status 選擇從服務器 Parameters Either host (string) and port (int), or no parameter to stop being a slave. 主機(string)和端口(int),或沒有參數再也不是一個從服務器。 Return value BOOL: TRUE in case of success, FALSE in case of failure. Example $redis->slaveof('10.0.1.7', 6379); $redis->slaveof();
object 命令/方法/函數 Describes the object pointed to by a key. 聲明一個對象,並指向KEY。 Parameters The information to retrieve (string) and the key (string). Info can be one of the following: "encoding" "refcount" "idletime" Return value STRING for "encoding", LONG for "refcount" and "idletime", FALSE if the key doesn't exist. Example $redis->object("encoding", "l"); // → ziplist $redis->object("refcount", "l"); // → 1 $redis->object("idletime", "l"); // → 400 (in seconds, with a precision of 10 seconds).
save 命令/方法/函數 Performs a synchronous save. 同步執行寫入到磁盤。即手動觸發將內存中的數據持久化到磁盤中,一般用於RDB持久化的模式下。(跟bgsave相似,不一樣的是,bgsave會單獨起一個進程進行備份持久化。詳細請參考:https://www.daixiaorui.com/read/230.html) Parameters None. Return value BOOL: TRUE in case of success, FALSE in case of failure. If a save is already running, this command will fail and return FALSE. Example $redis->save();
bgsave 命令/方法/函數 Performs a background save. 異步執行寫入到磁盤。即手動觸發將內存中的數據持久化到磁盤中,一般用於RDB持久化的模式下。(跟save相似,不一樣的是,save是同步的,會阻塞進程。詳細區別請參考:https://www.daixiaorui.com/read/230.html) Parameters None. Return value BOOL: TRUE in case of success, FALSE in case of failure. If a save is already running, this command will fail and return FALSE. Example $redis->bgSave();
lastSave 命令/方法/函數 Description Returns the timestamp of the last disk save. 返回最後一次數據磁盤持久化的時間戳。 Parameters None. Return value INT: timestamp. int: 時間戳。 Example $redis->lastSave();
type 命令/方法/函數 Description Returns the type of data pointed by a given key. 返回KEY所指向的VALUE的數據類型。 Parameters Key: key Return value Depending on the type of the data pointed by the key, this method will return the following value: 根據所指向的數據的類型,此方法將返回如下值: string: Redis::REDIS_STRING set: Redis::REDIS_SET list: Redis::REDIS_LIST zset: Redis::REDIS_ZSET hash: Redis::REDIS_HASH other: Redis::REDIS_NOT_FOUND Example $redis->type('key');
flushDB 命令/方法/函數 Description Removes all entries from the current database. 強制刷新當前DB(生成環境請慎用,會清掉當前DB中的全部key)。 清除全部DB中的key:flushAll Parameters None. Return value BOOL: Always TRUE. Example $redis->flushDB();
flushAll 命令/方法/函數 Description Removes all entries from all databases. 強制刷新全部DB(生成環境請慎用,會清掉全部DB中的key)。 清除當前DB中的key:flushDB Parameters None. Return value BOOL: Always TRUE. Example $redis->flushAll();
sort 命令/方法/函數 Description 篩選 Parameters Key: key Options: array(key => value, ...) - optional, with the following keys and values: 'by' => 'some_pattern_*', 'limit' => array(0, 1), 'get' => 'some_other_pattern_*' or an array of patterns, 'sort' => 'asc' or 'desc', 'alpha' => TRUE, 'store' => 'external-key' Return value An array of values, or a number corresponding to the number of elements stored if that was used. Example $redis->delete('s'); $redis->sadd('s', 5); $redis->sadd('s', 4); $redis->sadd('s', 2); $redis->sadd('s', 1); $redis->sadd('s', 3); var_dump($redis->sort('s')); // 1,2,3,4,5 var_dump($redis->sort('s', array('sort' => 'desc'))); // 5,4,3,2,1 var_dump($redis->sort('s', array('sort' => 'desc', 'store' => 'out'))); // (int)5
info 命令/方法/函數 Description Returns an associative array from REDIS that provides information about the server. Passing no arguments to INFO will call the standard REDIS INFO command, which returns information such as the following: 返回redis的相關係統信息,相似於PHP的PHPINFO();能夠選擇參數,按照選擇的參數返回相應的信息,也能夠不寫參數,返回全部的信息。 info能夠查看redis當前佔用的內存大小、當前系統信息、持久化信息、key數量等。 redis_version arch_bits uptime_in_seconds uptime_in_days connected_clients connected_slaves used_memory 內存使用狀況 changes_since_last_save bgsave_in_progress last_save_time total_connections_received total_commands_processed role You can pass a variety of options to INFO (per the Redis documentation), which will modify what is returned. 你能夠經過多種選擇的信息(每使用文檔),這將是返回修改。 Parameters option: The option to provide redis (e.g. "COMMANDSTATS", "CPU") option:redis提供一些選項(如"COMMANDSTATS", "CPU") Example $redis->info(); /* standard redis INFO command */ $redis->info("COMMANDSTATS"); /* Information on the commands that have been run (>=2.6 only) $redis->info("CPU"); /* just CPU information from Redis INFO */
resetStat 命令/方法/函數 Description Resets the statistics reported by Redis using the INFO command (info() function). 使用info()重置靜態的日誌。 These are the counters that are reset: Keyspace hits Keyspace misses Number of commands processed Number of connections received Number of expired keys Parameters None. Return value BOOL: TRUE in case of success, FALSE in case of failure. Example $redis->resetStat();
ttl 命令/方法/函數 Description Returns the time to live left for a given key, in seconds. If the key doesn't exist, FALSE is returned. pttl returns a time in milliseconds. 取得一個KEY已經存在的時間。若是這個KEY不存在,則返回FLASE。PTTL使用毫秒爲單位。 Parameters Key: key Return value Long, the time left to live in seconds. Example $redis->ttl('key');
pttl 命令/方法/函數 Description Returns the time to live left for a given key, in milliseconds. If the key doesn't exist, FALSE is returned. ttl in seconds returns a time . 取得一個KEY已經存在的時間,單位是毫秒。若是這個KEY不存在,則返回FLASE。TTL使用毫秒爲單位。 Parameters Key: key Return value Long, the time left to live in milliseconds. Example $redis->pttl('key');
persist 命令/方法/函數 Description Remove the expiration timer from a key. 刪除一個KEY的生命週期設置。 Parameters Key: key Return value BOOL: TRUE if a timeout was removed, FALSE if the key didn’t exist or didn’t have an expiration timer. 若是確實有生命週期而且成功移除,則返回TRUE。若是KEY不存在,或者KEY沒有生命週期則返回FLASE。 Example $redis->persist('key');
config 命令/方法/函數 Description Get or Set the redis config keys. 取得或者設置REIDS系統配置KEYS。 Parameters operation (string) either GET or SET key string for SET, glob-pattern for GET. See http://redis.io/commands/config-get for examples. value optional string (only for SET) Return value Associative array for GET, key -> value bool for SET Examples $redis->config("GET", "*max-*-entries*"); $redis->config("SET", "dir", "/var/run/redis/dumps/");
eval 命令/方法/函數 Description Evaluate a LUA script serverside 在服務器端執行LUA腳本 Parameters script string. args array, optional. num_keys int, optional. Return value Mixed. What is returned depends on what the LUA script itself returns, which could be a scalar value (int/string), or an array. Arrays that are returned can also contain other arrays, if that's how it was set up in your LUA script. If there is an error executing the LUA script, the getLastError() function can tell you the message that came back from Redis (e.g. compile error). 這個函數返回的結果是函數傳輸的LUA腳本的執行結果。結果能夠是一個普通的數據類型,也可使一個數組,數組內也能夠嵌套數組。不管返回的結果是什麼,都是取決於你的LUA腳本是如何執行的。若是你傳輸的LUA腳本存在錯誤,那麼getLastError()可以返回出REDIS對於這個錯誤的具體消息。 Examples $redis->eval("return 1"); // Returns an integer: 1 $redis->eval("return {1,2,3}"); // Returns Array(1,2,3) $redis->del('mylist'); $redis->rpush('mylist','a'); $redis->rpush('mylist','b'); $redis->rpush('mylist','c'); // Nested response: Array(1,2,3,Array('a','b','c')); $redis->eval("return {1,2,3,redis.call('lrange','mylist',0,-1)}}");
evalSha 命令/方法/函數 Description Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself. In order to run this command Redis will have to have already loaded the script, either by running it or via the SCRIPT LOAD command. Parameters script_sha string. The sha1 encoded hash of the script you want to run. args array, optional. Arguments to pass to the LUA script. num_keys int, optional. The number of arguments that should go into the KEYS array, vs. the ARGV array when Redis spins the script Return value Mixed. See EVAL Examples $script = 'return 1'; $sha = $redis->script('load', $script); $redis->evalSha($sha); // Returns 1
script 命令/方法/函數 Description Execute the Redis SCRIPT command to perform various operations on the scripting subsystem. 執行Redis腳本命令來執行各類操做。 Return value SCRIPT LOAD will return the SHA1 hash of the passed script on success, and FALSE on failure. SCRIPT FLUSH should always return TRUE SCRIPT KILL will return true if a script was able to be killed and false if not SCRIPT EXISTS will return an array with TRUE or FALSE for each passed script Usage $redis->script('load', $script); $redis->script('flush'); $redis->script('kill'); $redis->script('exists', $script1, [$script2, $script3, ...]);
getLastError 命令/方法/函數 Description The last error message (if any) returned from a SCRIPT call 取得最後的錯誤消息。 Parameters none Return Value A string with the last returned script based error message, or NULL if there is no error 若是有錯誤,返回一個字符串;若是沒有錯誤,返回NULL。 Examples $redis->eval('this-is-not-lua'); $err = $redis->getLastError(); // "ERR Error compiling script (new function): user_script:1: '=' expected near '-'"
_prefix 命令/方法/函數 Description A utility method to prefix the value with the prefix setting for phpredis. 用於給VALUE加入前綴 Parameters value string. The value you wish to prefix Return value If a prefix is set up, the value now prefixed. If there is no prefix, the value will be returned unchanged. 若是設置了前綴,值爲當前前綴。若是沒有前綴,返回值不變。 Examples $redis->setOpt(Redis::OPT_PREFIX, 'my-prefix:'); $redis->_prefix('my-value'); // Will return 'my-prefix:my-value'
_unserialize 命令/方法/函數 Description A utility method to unserialize data with whatever serializer is set up. If there is no serializer set, the value will be returned unchanged. If there is a serializer set up, and the data passed in is malformed, an exception will be thrown. This can be useful if phpredis is serializing values, and you return something from redis in a LUA script that is serialized. 反序列化函數,用於序列化的SET類型數據。若是參數不是序列化的SET,那麼會直接返回。若是是一個序列化的SET,但不是PHP-REDIS序列化的格式,函數將拋出一個異常。 Parameters value string. The value to be unserialized Examples $redis->setOpt(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); $redis->_unserialize('a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}'); // Will return Array(1,2,3)
dump 命令/方法/函數 Description Dump a key out of a redis database, the value of which can later be passed into redis using the RESTORE command. The data that comes out of DUMP is a binary representation of the key as Redis stores it. 把一個KEY從REIDS中銷燬(可是這個銷燬不是物理意義上銷燬),這個被銷燬的VALUE,可使用RESTORE函數恢復出來。使用DUMP銷燬的VALUE,函數將返回這個數據在REIDS中的二進制內存地址。 Parameters key string Return value The Redis encoded value of the key, or FALSE if the key doesn't exist Examples $redis->set('foo', 'bar'); $val = $redis->dump('foo'); // $val will be the Redis encoded key value
restore 命令/方法/函數 Description Restore a key from the result of a DUMP operation. 恢復DUMP函數銷燬的VALUE到一個新的KEY上。 Parameters key string. The key name ttl integer. How long the key should live (if zero, no expire will be set on the key) value string (binary). The Redis encoded key value (from DUMP) Examples $redis->set('foo', 'bar'); $val = $redis->dump('foo'); $redis->restore('bar', 0, $val); // The key 'bar', will now be equal to the key 'foo'
migrate 命令/方法/函數 Description Migrates a key to a different Redis instance. 遷移一個KEY島不一樣的REIDS實例。 Parameters host string. The destination host port integer. The TCP port to connect to. key string. The key to migrate. destination-db integer. The target DB. timeout integer. The maximum amount of time given to this transfer. Examples $redis->migrate('backup', 6379, 'foo', 0, 3600);
time 命令/方法/函數 Description Return the current Redis server time. 返回當前REDIS服務器的生存時間。 Parameters (none) Return value If successfull, the time will come back as an associative array with element zero being the unix timestamp, and element one being microseconds. Examples $redis->time();