redis 通用函数

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();
05-11 11:03