php-redis中文帮助手册

php-redis中文帮助手册，是我突然抽风搞出来的参考手册，其中一些翻译部分也借鉴了网上许多的资料。但实话说，我无法判断借鉴或者COPY的一些翻译到底原作者是是谁了。就在这里一并谢谢了吧。

我的英文水平及对Redis的使用经验都是一般般的，所以肯定有许多地方的翻译理解，及函数分类会有错误。大家就凑合着用用吧。也希望对于帮助文档翻译有经验的各位大神们多多帮助，有好的翻译就发给我，我会及时更新帮助文档~~~希望与大家多多交流

我的联系方式：

QQ:104732401

EMAIL:cniiliuqi@126.com

Blog:http://my.oschina.net/cniiliuqi


系统及通用函数

 这个分类里的函数多于Redis本身相关的一些操作。如持久化数据，取得Redis的各类信息，Redis的各种运行状态等等。


construct

Redis::__construct

Description

Creates a Redis client

创建一个Redis客户端

Example
$redis = new Redis();


connect, open

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, popen

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.

选择数据库

Parameters

INTEGER: dbindex, the database number to switch to.

整数值：数据库索引，数据库的ID

Return value

TRUE in case of success, FALSE in case of failure.

Example

(See following function)


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.

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, renameKey

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


setTimeout, expire, pexpire

Description

Sets an expiration date (a timeout) on an item. pexpire requires a TTL in milliseconds.

给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->setTimeout('x', 3); // x will disappear in 3 seconds.
sleep(5);               // wait 5 seconds
$redis->get('x');       // will return `FALSE`, as 'x' has expired.


expireAt, pexpireAt

Description

Sets an expiration date (a timestamp) on an item. pexpireAt requires a timestamp in milliseconds.

给一个KEY设置一个生命周期，单位是UNIX的时间戳。

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.


keys, getKeys

Description

Returns the keys that match a certain pattern.

返回某种计算模式取得的KEYS。

Description
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.
$keyWithUserPrefix = $redis->keys('user*');


dbSize

Description

Returns the current database's size.

返回当前DB的KEY的数量

Parameters

None.

Return value

INTEGER: DB size, in number of keys.

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以明码的形式在网络中传输。

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

Description

Changes the slave status

选择从服务器

Parameters

Either host (string) and port (int), or no parameter to stop being a slave.

Return value

BOOL: TRUE in case of success, FALSE in case of failure.

Example
$redis->slaveof('10.0.1.7', 6379);
/* ... */
$redis->slaveof();


object

Description

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

Description

Performs a synchronous save.

同步执行写入到磁盘。

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

Description

Performs a background save.

异步保存到磁盘。

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.

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。

Parameters

None.

Return value

BOOL: Always TRUE.

Example
$redis->flushDB();


flushAll

Description

Removes all entries from all databases.

强制刷新所有的DB。

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();可以选择参数，按照选择的参数返回相应的信息，也可以不写参数，返回所有的信息。

  • 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")

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, pttl

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');


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脚本命令来执行各种操作。

Usage
$redis->script('load', $script);
$redis->script('flush');
$redis->script('kill');
$redis->script('exists', $script1, [$script2, $script3, ...]);
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


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

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();


String数据类型函数

 string是redis最基本的类型，而且string类型是二进制安全的。意思是redis的string可以包含任何数据。比如jpg图片或者序列化的对象


get

Description

Get the value related to the specified key

取得与指定的键值相关联的值

Parameters

key

Return Value

String or Bool: If key didn't exist, FALSE is returned. Otherwise, the value related to this key is returned.

返回相关值或者BOOL值，如果KEY不存在，返回FALSE。如果有相关的KEY和值返回值。

Examples
$redis->get('key');


set

Description

Set the string value in argument as value of the key.

设置值到KEY

Parameters

Key
Value
Timeout (optional). Calling SETEX is preferred if you want a timeout.

Return value

Bool TRUE if the command is successful.

Examples
$redis->set('key', 'value');


setex, psetex

Description

Set the string value in argument as value of the key, with a time to live. PSETEX uses a TTL in milliseconds.

设置一个有生命周期的KEY-VALUE,psetex()使用的周期单位为毫秒。

Parameters

Key TTL Value

Return value

Bool TRUE if the command is successful.

Examples
$redis->setex('key', 3600, 'value'); // sets key → value, with 1h TTL.
$redis->psetex('key', 100, 'value'); // sets key → value, with 0.1 sec TTL.


setnx

Description

Set the string value in argument as value of the key if the key doesn't already exist in the database.

setnx用于设置一个KEY-VALUE，这个函数会先判断Redis中是否有这个KEY，如果没有就SET，有就返回False。

Parameters

key value

Return value

Bool TRUE in case of success, FALSE in case of failure.

Examples
$redis->setnx('key', 'value'); /* return TRUE */
$redis->setnx('key', 'value'); /* return FALSE */


del, delete

Description

Remove specified keys.

移除已经存在KEYS

Parameters

An array of keys, or an undefined number of parameters, each a key: key1 key2 key3 ... keyN

可以是一个KEYS的数组，或者一个未定义的数字参数，或者一个一个的写KEY

Return value

Long Number of keys deleted.

返回删除KEY-VALUE的数量

Examples
$redis->set('key1', 'val1');
$redis->set('key2', 'val2');
$redis->set('key3', 'val3');
$redis->set('key4', 'val4');

$redis->delete('key1', 'key2'); /* return 2 */
$redis->delete(array('key3', 'key4')); /* return 2 */


getSet

Description

Sets a value and returns the previous entry at that key.

设置一个VALUE 并且返回该KEY当前的VALUE。

Parameters

Key: key

STRING: value

Return value

A string, the previous value located at this key.

Example
$redis->set('x', '42');
$exValue = $redis->getSet('x', 'lol');  // return '42', replaces x by 'lol'
$newValue = $redis->get('x')'       // return 'lol'


multi, exec, discard.

Description

Enter and exit transactional mode.

进入、退出事务处理模式。

Parameters

(optional) Redis::MULTI or Redis::PIPELINE. Defaults to Redis::MULTI. A Redis::MULTI block of commands runs as a single transaction; a Redis::PIPELINE block is simply transmitted faster to the server, but without any guarantee of atomicity. discardcancels a transaction.

multi函数的参数选项为Redis::MULTI或者是Redis::PIPELINE.默认的是参数是Redis::MULTI。

Redis::MULTI将多个操作当做一个事务来处理。Redis::PIPELINE将作为一个简单快速的处理通道给服务器进行处理，但是不保证处理数据的原子性。

discard()函数取消一个事物处理模式。

Return value

multi() returns the Redis instance and enters multi-mode. Once in multi-mode, all subsequent method calls return the same object until exec() is called.

multi()返回一个Redis实例，并且这个实例进入到了事务处理模式（批量处理）。当进入到事务处理模式，所有的方法调用都将返回相同的Redis实例，一直到exec()被调用执行事务处理。

Example
$ret = $redis->multi()
    ->set('key1', 'val1')
    ->get('key1')
    ->set('key2', 'val2')
    ->get('key2')
    ->exec();

/*
$ret == array(
    0 => TRUE,
    1 => 'val1',
    2 => TRUE,
    3 => 'val2');
*/


watch, unwatch

Description

Watches a key for modifications by another client. If the key is modified between WATCH and EXEC, the MULTI/EXEC transaction will fail (return FALSE). unwatch cancels all the watching of all keys by this client.

监控一个KEY是否被其他的客户端修改。如果KEY在调用watch()和exec()之间被修改，那么批量处理最终的exec()执行将失败。unwatch()取消对于所有KEY值的监控操作针对于这个Redis实例。通过一些实验，这个函数的效果其实并没有那么好，或者说不能够准确的去监控。

Parameters

keys: a list of keys

Example
$redis->watch('x');
/* long code here during the execution of which other clients could well modify `x` */
$ret = $redis->multi()
    ->incr('x')
    ->exec();
/*
$ret = FALSE if x has been modified between the call to WATCH and the call to EXEC.
*/


subscribe

Description

Subscribe to channels. Warning: this function will probably change in the future.

方法回调函数,注意：该方法在将来有可能被修改。

Parameters

channels: an array of channels to subscribe to
callback: either a string or an array($instance, 'method_name'). The callback function receives 3 parameters: the redis instance, the channel name, and the message.

Example
function f($redis, $chan, $msg) {
    switch($chan) {
        case 'chan-1':
            ...
            break;

        case 'chan-2':
            ...
            break;

        case 'chan-2':
            ...
            break;
    }
}

$redis->subscribe(array('chan-1', 'chan-2', 'chan-3'), 'f'); // subscribe to 3 chans


publish

Description

Publish messages to channels. Warning: this function will probably change in the future.

Parameters

channel: a channel to publish to
messsage: string

Example
$redis->publish('chan-1', 'hello, world!'); // send message.


exists

Description

Verify if the specified key exists.

验证一个指定的KEY是否存在

Parameters

key

Return value

BOOL: If the key exists, return TRUE, otherwise return FALSE.

Examples
$redis->set('key', 'value');
$redis->exists('key'); /*  TRUE */
$redis->exists('NonExistingKey'); /* FALSE */


incr, incrBy

Description

Increment the number stored at key by one. If the second argument is filled, it will be used as the integer value of the increment.

对指定的KEY的值自增1。如何填写了第二个参数，将把第二个参数自增给KEY的值。

Parameters

key
value: value that will be added to key (only for incrBy)

Return value

INT the new value

返回新的INT数值

Examples
$redis->incr('key1'); /* key1 didn't exists, set to 0 before the increment */
                      /* and now has the value 1  */

$redis->incr('key1'); /* 2 */
$redis->incr('key1'); /* 3 */
$redis->incr('key1'); /* 4 */
$redis->incrBy('key1', 10); /* 14 */


incrByFloat

Description

Increment the key with floating point precision.

自增一个浮点型的数值。

Parameters

key
value: (float) value that will be added to the key

Return value

FLOAT the new value

Examples
$redis->incrByFloat('key1', 1.5); /* key1 didn't exist, so it will now be 1.5 */

$redis->incrByFloat('key1', 1.5); /* 3 */
$redis->incrByFloat('key1', -1.5); /* 1.5 */
$redis->incrByFloat('key1', 2.5); /* 3.5 */


decr, decrBy

Description

Decrement the number stored at key by one. If the second argument is filled, it will be used as the integer value of the decrement.

对指定的KEY的值自减1。如何填写了第二个参数，将把第二个参数自减给KEY的值。
Parameters

key
value: value that will be substracted to key (only for decrBy)

Return value

INT the new value

Examples
$redis->decr('key1'); /* key1 didn't exists, set to 0 before the increment */
                      /* and now has the value -1  */

$redis->decr('key1'); /* -2 */
$redis->decr('key1'); /* -3 */
$redis->decrBy('key1', 10); /* -13 */


mGet, getMultiple

Description

Get the values of all the specified keys. If one or more keys dont exist, the array will contain FALSE at the position of the key.

取得所有指定KEYS的值，如果一个或者更多的KEYS不存在，那么返回的ARRAY中将在相应的KEYS的位置填充FALSE。

Parameters

Array: Array containing the list of the keys

数组:一个KEYS的数组

Return value

Array: Array containing the values related to keys in argument

数组：返回相应的KEYS的值

Examples
$redis->set('key1', 'value1');
$redis->set('key2', 'value2');
$redis->set('key3', 'value3');
$redis->mGet(array('key1', 'key2', 'key3')); /* array('value1', 'value2', 'value3');
$redis->mGet(array('key0', 'key1', 'key5')); /* array(`FALSE`, 'value2', `FALSE`);


append

Description

Append specified string to the string stored in specified key.

添加指定的字符串到指定的字符串KEY。

Parameters

Key Value

Return value

INTEGER: Size of the value after the append

返回添加后KEY的SIZE

Example
$redis->set('key', 'value1');
$redis->append('key', 'value2'); /* 12 */
$redis->get('key'); /* 'value1value2' */


getRange

getRange (substr also supported but deprecated in redis)

Description

Return a substring of a larger string

返回字符串的一部分

Parameters

key start end

Return value

STRING: the substring

Example
$redis->set('key', 'string value');
$redis->getRange('key', 0, 5); /* 'string' */
$redis->getRange('key', -5, -1); /* 'value' */


setRange

Description

Changes a substring of a larger string.

修改字符串的一部分。

Parameters

key
offset
value

Return value

STRING: the length of the string after it was modified.

Example
$redis->set('key', 'Hello world');
$redis->setRange('key', 6, "redis"); /* returns 11 */
$redis->get('key'); /* "Hello redis" */


strlen

Description

Get the length of a string value.

返回字符串的长度。

Parameters

key

Return value

INTEGER

Example
$redis->set('key', 'value');
$redis->strlen('key'); /* 5 */


getBit

Description

Return a single bit out of a larger string

Parameters

key
offset

Return value

LONG: the bit value (0 or 1)

Example
$redis->set('key', "\x7f"); // this is 0111 1111
$redis->getBit('key', 0); /* 0 */
$redis->getBit('key', 1); /* 1 */


setBit

Description

Changes a single bit of a string.

Parameters

key
offset
value: bool or int (1 or 0)

Return value

LONG: 0 or 1, the value of the bit before it was set.

Example
$redis->set('key', "*");    // ord("*") = 42 = 0x2f = "0010 1010"
$redis->setBit('key', 5, 1); /* returns 0 */
$redis->setBit('key', 7, 1); /* returns 0 */
$redis->get('key'); /* chr(0x2f) = "/" = b("0010 1111") */


bitop

Description

Bitwise operation on multiple keys.

Parameters

operation: either "AND", "OR", "NOT", "XOR"
ret_key: return key
key1
key2...

Return value

LONG: The size of the string stored in the destination key.


bitcount

Description

Count bits in a string.

Parameters

key

Return value

LONG: The number of bits set to 1 in the value behind the input key.


mset, msetnx

Description

Sets multiple key-value pairs in one atomic command. MSETNX only returns TRUE if all the keys were set (see SETNX).

批量设置多个KEY-VALUE。如果所有的KEYS都被设置成功，如果这些KEY-VALUE都SET成功,使用msetnx将仅仅返回一个TURE，而如果有一个是已经存在的KEY，则所有的操作都不被执行。

Parameters

Pairs: array(key => value, ...)

Return value

Bool TRUE in case of success, FALSE in case of failure.

Example
$redis->mset(array('key0' => 'value0', 'key1' => 'value1'));
var_dump($redis->get('key0'));
var_dump($redis->get('key1'));

Output:

string(6) "value0"
string(6) "value1"


List数据类型相关函数

 redis的list类型其实就是一个每个子元素都是string类型的双向链表。


lPush

Description

Adds the string value to the head (left) of the list. Creates the list if the key didn't exist. If the key exists and is not a list, FALSE is returned.

添加一个字符串值到LIST容器的顶部（左侧），如果KEY不存在，曾创建一个LIST容器，如果KEY存在并且不是一个LIST容器，那么返回FLASE。

Parameters

key
value String, value to push in key

Return value

LONG The new length of the list in case of success, FALSE in case of Failure.

返回LIST容器最新的长度，如果ADD成功。失败则返回FALSE。

Examples
$redis->delete('key1');
$redis->lPush('key1', 'C'); // returns 1
$redis->lPush('key1', 'B'); // returns 2
$redis->lPush('key1', 'A'); // returns 3
/* key1 now points to the following list: [ 'A', 'B', 'C' ] */


rPush

Description

Adds the string value to the tail (right) of the list. Creates the list if the key didn't exist. If the key exists and is not a list, FALSE is returned.

添加一个字符串值到LIST容器的底部（右侧），如果KEY不存在，曾创建一个LIST容器，如果KEY存在并且不是一个LIST容器，那么返回FLASE。
Parameters

key
value String, value to push in key

Return value

LONG The new length of the list in case of success, FALSE in case of Failure.

返回LIST容器最新的长度，如果ADD成功。失败则返回FALSE。
Examples
$redis->delete('key1');
$redis->rPush('key1', 'A'); // returns 1
$redis->rPush('key1', 'B'); // returns 2
$redis->rPush('key1', 'C'); // returns 3
/* key1 now points to the following list: [ 'A', 'B', 'C' ] */


lPushx

Description

Adds the string value to the head (left) of the list if the list exists.

添加一个VALUE到LIST容器的顶部（左侧）如果这个LIST存在的话。

Parameters

key
value String, value to push in key

Return value

LONG The new length of the list in case of success, FALSE in case of Failure.

如果ADD成功， 返回LIST容器最新的长度。失败则返回FALSE。

Examples
$redis->delete('key1');
$redis->lPushx('key1', 'A'); // returns 0
$redis->lPush('key1', 'A'); // returns 1
$redis->lPushx('key1', 'B'); // returns 2
$redis->lPushx('key1', 'C'); // returns 3
/* key1 now points to the following list: [ 'A', 'B', 'C' ] */


rPushx

Description

Adds the string value to the tail (right) of the list if the ist exists. FALSE in case of Failure.

添加一个VALUE到LIST容器的底部（右侧）如果这个LIST存在的话。
Parameters

key
value String, value to push in key

Return value

LONG The new length of the list in case of success, FALSE in case of Failure.

如果ADD成功， 返回LIST容器最新的长度。失败则返回FALSE。
Examples
$redis->delete('key1');
$redis->rPushx('key1', 'A'); // returns 0
$redis->rPush('key1', 'A'); // returns 1
$redis->rPushx('key1', 'B'); // returns 2
$redis->rPushx('key1', 'C'); // returns 3
/* key1 now points to the following list: [ 'A', 'B', 'C' ] */


lPop

Description

Return and remove the first element of the list.

返回LIST顶部（左侧）的VALUE，并且从LIST中把该VALUE弹出。

Parameters

key

Return value

STRING if command executed successfully BOOL FALSE in case of failure (empty list)

取得VALUE成功，返回TURE。如果是一个空LIST则返回FLASE。

Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->lPop('key1'); /* key1 => [ 'B', 'C' ] */


rPop

Description

Returns and removes the last element of the list.

返回LIST底部（右侧）的VALUE，并且从LIST中把该VALUE弹出。
Parameters

key

Return value

STRING if command executed successfully BOOL FALSE in case of failure (empty list)

取得VALUE成功，返回TURE。如果是一个空LIST则返回FLASE。
Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->rPop('key1'); /* key1 => [ 'A', 'B' ] */


blPop, brPop

Description

Is a blocking lPop(rPop) primitive. If at least one of the lists contains at least one element, the element will be popped from the head of the list and returned to the caller. Il all the list identified by the keys passed in arguments are empty, blPop will block during the specified timeout until an element is pushed to one of those lists. This element will be popped.

lpop命令的block 版本即阻塞版本。如果LIST容器中有VAULE，将会返回ARRAY（'listName''element'）。如果TIMEOUT参数为空，那么如果LIST为空，blPop或者brPop将或结束调用。如果设置了timeout参数，blPop或者brPop将被挂起暂停运行TIMEOUT参数的时间，在此期间如果LIST被PUSH了元素，将在TIMEOUT时间结束后，被POP出来。

Parameters

ARRAY Array containing the keys of the lists INTEGER Timeout Or STRING Key1 STRING Key2 STRING Key3 ... STRING KeynINTEGER Timeout

Return value

ARRAY array('listName', 'element')

Example
/* Non blocking feature */
$redis->lPush('key1', 'A');
$redis->delete('key2');

$redis->blPop('key1', 'key2', 10); /* array('key1', 'A') */
/* OR */
$redis->blPop(array('key1', 'key2'), 10); /* array('key1', 'A') */

$redis->brPop('key1', 'key2', 10); /* array('key1', 'A') */
/* OR */
$redis->brPop(array('key1', 'key2'), 10); /* array('key1', 'A') */

/* Blocking feature */

/* process 1 */
$redis->delete('key1');
$redis->blPop('key1', 10);
/* blocking for 10 seconds */

/* process 2 */
$redis->lPush('key1', 'A');

/* process 1 */
/* array('key1', 'A') is returned*/


lSize

Description

Returns the size of a list identified by Key. If the list didn't exist or is empty, the command returns 0. If the data type identified by Key is not a list, the command return FALSE.

根据KEY返回该KEY代表的LIST的长度，如果这个LIST不存在或者为空，那么ISIZE返回0，如果指定的KEY的数据类型不是LIST或者不为空，那么返回FALSE。所以在这里多说一句，当用ISize返回判断值的时候，===就有用处了，这里FLASE和0是两个概念了。

Parameters

Key

Return value

LONG The size of the list identified by Key exists.

如果KEY存在并且为LIST且有元素，那么返回KEY的长度，为空或者不存在返回0。

BOOL FALSE if the data type identified by Key is not list

如果KEY的数据类型不为空或者LIST，则返回FALSE。

Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->lSize('key1');/* 3 */
$redis->rPop('key1');
$redis->lSize('key1');/* 2 */


lIndex, lGet

Description

Return the specified element of the list stored at the specified key. 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ... Return FALSE in case of a bad index or a key that doesn't point to a list.

根据索引值返回指定KEY LIST中的元素。0为第一个元素，1为第二个元素。-1为倒数第一个元素，-2为倒数第二个元素。如果指定了一个不存在的索引值，则返回FLASE。

Parameters

key index

Return value

String the element at this index
Bool FALSE if the key identifies a non-string data type, or no value corresponds to this index in the list Key.

Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->lGet('key1', 0); /* 'A' */
$redis->lGet('key1', -1); /* 'C' */
$redis->lGet('key1', 10); /* `FALSE` */


lSet

Description

Set the list at index with the new value.

根据索引值设置新的VAULE

Parameters

key index value

Return value

BOOL TRUE if the new value is setted. FALSE if the index is out of range, or data type identified by key is not a list.

如果设置成功返回TURE，如果KEY所指向的不是LIST，或者索引值超出LIST本身的长度范围，则返回flase。

Iset函数更像是UPDATE或者EDIT的概念，而不是INSERT或者ADD的概念，顾只能在LIST本身的长度范围内，而不能超出。

Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->lGet('key1', 0); /* 'A' */
$redis->lSet('key1', 0, 'X');
$redis->lGet('key1', 0); /* 'X' */


IRange,IGetRange

lRange, lGetRange

Description

Returns the specified elements of the list stored at the specified key in the range [start, end]. start and stop are interpretated as indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ...

取得指定索引值范围内的所有元素。

Parameters

key start end

Return value

Array containing the values in specified range.

Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C');
$redis->lRange('key1', 0, -1); /* array('A', 'B', 'C') */


lTrim, listTrim

Description

Trims an existing list so that it will contain only a specified range of elements.

它将截取LIST中指定范围内的元素组成一个新的LIST并指向KEY。简短解说就是截取LIST。

这个可不是JS，或者PHP中清空空格的意思。

Parameters

key start stop

Return value

Array
Bool return FALSE if the key identify a non-list value.

Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C');
$redis->lRange('key1', 0, -1); /* array('A', 'B', 'C') */
$redis->lTrim('key1', 0, 1);
$redis->lRange('key1', 0, -1); /* array('A', 'B') */


lRem, lRemove

Description

Removes the first count occurences of the value element from the list. If count is zero, all the matching elements are removed. If count is negative, elements are removed from tail to head.

IRem,IRemove函数，首先要去判断count参数，如果count参数为0，那么所有符合删除条件的元素都将被移除。如果count参数为整数,将从左至右删除count个符合条件的元素，如果为负数则从右至左删除count个符合条件的元素。

Note: The argument order is not the same as in the Redis documentation. This difference is kept for compatibility reasons.

函数参数的顺序不一定要一致，这样做是为了保持兼容性。

Parameters

key
value
count

Return value

LONG the number of elements to remove
BOOL FALSE if the value identified by key is not a list.

Example
$redis->lPush('key1', 'A');
$redis->lPush('key1', 'B');
$redis->lPush('key1', 'C');
$redis->lPush('key1', 'A');
$redis->lPush('key1', 'A');

$redis->lRange('key1', 0, -1); /* array('A', 'A', 'C', 'B', 'A') */
$redis->lRem('key1', 'A', 2); /* 2 */
$redis->lRange('key1', 0, -1); /* array('C', 'B', 'A') */


lInsert

Description

Insert value in the list before or after the pivot value. the parameter options specify the position of the insert (before or after). If the list didn't exists, or the pivot didn't exists, the value is not inserted.

在指定LIST中的指定中枢VALUE的左侧或者右侧插入VALUE。如果这个LIST不存在，或者这个pivot(key position)不存在，那么这个VALUE不会被插入。

Parameters

key position Redis::BEFORE | Redis::AFTER pivot value

Return value

The number of the elements in the list, -1 if the pivot didn't exists.

Example
$redis->delete('key1');
$redis->lInsert('key1', Redis::AFTER, 'A', 'X'); /* 0 */

$redis->lPush('key1', 'A');
$redis->lPush('key1', 'B');
$redis->lPush('key1', 'C');

$redis->lInsert('key1', Redis::BEFORE, 'C', 'X'); /* 4 */
$redis->lRange('key1', 0, -1); /* array('A', 'B', 'X', 'C') */

$redis->lInsert('key1', Redis::AFTER, 'C', 'Y'); /* 5 */
$redis->lRange('key1', 0, -1); /* array('A', 'B', 'X', 'C', 'Y') */

$redis->lInsert('key1', Redis::AFTER, 'W', 'value'); /* -1 */


rpoplpush

rpoplpush (redis >= 1.1)

Description

Pops a value from the tail of a list, and pushes it to the front of another list. Also return this value.

从源LIST的最后弹出一个元素，并且把这个元素从目标LIST的顶部（左侧）压入目标LIST。

Parameters

Key: srckey
Key: dstkey

Return value

STRING The element that was moved in case of success, FALSE in case of failure.

Example
$redis->delete('x', 'y');

$redis->lPush('x', 'abc');
$redis->lPush('x', 'def');
$redis->lPush('y', '123');
$redis->lPush('y', '456');

// move the last of x to the front of y.
var_dump($redis->rpoplpush('x', 'y'));
var_dump($redis->lRange('x', 0, -1));
var_dump($redis->lRange('y', 0, -1));

Output:

string(3) "abc"
array(1) {
  [0]=>
  string(3) "def"
}
array(3) {
  [0]=>
  string(3) "abc"
  [1]=>
  string(3) "456"
  [2]=>
  string(3) "123"
}


brpoplpush

Description

A blocking version of rpoplpush, with an integral timeout in the third parameter.

rpoplpush的阻塞版本，这个版本有第三个参数用于设置阻塞时间，即如果源LIST为空，那么可以阻塞监听timeout的时间，如果有元素了则执行操作。

Parameters

Key: srckey
Key: dstkey
Long: timeout

Return value

STRING The element that was moved in case of success, FALSE in case of timeout.


Set数据类型相关函数

在Redis中，我们可以将Set类型看作为没有排序的字符集合，和List类型一样，我们也可以在该类型的数据值上执行添加、删除或判断某一元素是否存在等操作。需要说明的是，这些操作的时间复杂度为O(1)，即常量时间内完成次操作。Set可包含的最大元素数量是4294967295。

和List类型不同的是，Set集合中不允许出现重复的元素，这一点和C++标准库中的set容器是完全相同的。换句话说，如果多次添加相同元素，Set中将仅保留该元素的一份拷贝。和List类型相比，Set类型在功能上还存在着一个非常重要的特性，即在服务器端完成多个Sets之间的聚合计算操作，如unions、intersections和differences。由于这些操作均在服务端完成，因此效率极高，而且也节省了大量的网络IO开销。


sAdd

Description

Adds a value to the set value stored at key. If this value is already in the set, FALSE is returned.

添加一个VALUE到SET容器中，如果这个VALUE已经存在于SET中，那么返回FLASE。

Parameters

key value

Return value

BOOL TRUE if value didn't exist and was added successfully, FALSE if the value is already present.

如果VALUE不存在于SET中，那么ADDED成功，返回TRUE，负责返回FALSE。

Example
$redis->sAdd('key1' , 'member1'); /* TRUE, 'key1' => {'member1'} */
$redis->sAdd('key1' , 'member2'); /* TRUE, 'key1' => {'member1', 'member2'}*/
$redis->sAdd('key1' , 'member2'); /* FALSE, 'key1' => {'member1', 'member2'}*/


sRem, sRemove

Description

Removes the specified member from the set value stored at key.

移除指定的VALUE从SET容器中

Parameters

key member

Return value

BOOL TRUE if the member was present in the set, FALSE if it didn't.

Example
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/
$redis->sRem('key1', 'member2'); /* 'key1' => {'member1', 'member3'} */


sMove

Description

Moves the specified member from the set at srcKey to the set at dstKey.

移动一个指定的MEMBER从源SET到指定的另一个SET中。

Parameters

srcKey dstKey member

Return value

BOOL If the operation is successful, return TRUE. If the srcKey and/or dstKey didn't exist, and/or the member didn't exist in srcKey,FALSE is returned.

如果操作成功返回TRUE，如果源SET或者目标SET不存在，或者MEMBER不存在于源SET，那么返回FLASE。

Example
$redis->sAdd('key1' , 'member11');
$redis->sAdd('key1' , 'member12');
$redis->sAdd('key1' , 'member13'); /* 'key1' => {'member11', 'member12', 'member13'}*/
$redis->sAdd('key2' , 'member21');
$redis->sAdd('key2' , 'member22'); /* 'key2' => {'member21', 'member22'}*/
$redis->sMove('key1', 'key2', 'member13'); /* 'key1' =>  {'member11', 'member12'} */
                    /* 'key2' =>  {'member21', 'member22', 'member13'} */


sIsMember, sContains

Description

Checks if value is a member of the set stored at the key key.

检查VALUE是否是SET容器中的成员。

Parameters

key value

Return value

BOOL TRUE if value is a member of the set at key key, FALSE otherwise.

Example
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/

$redis->sIsMember('key1', 'member1'); /* TRUE */
$redis->sIsMember('key1', 'memberX'); /* FALSE */


sCard, sSize

Description

Returns the cardinality of the set identified by key.

返回SET容器的成员数

Parameters

key

Return value

LONG the cardinality of the set identified by key, 0 if the set doesn't exist.

Example
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/
$redis->sCard('key1'); /* 3 */
$redis->sCard('keyX'); /* 0 */


sPop

Description

Removes and returns a random element from the set value at Key.

随机返回一个元素，并且在SET容器中移除该元素。

Parameters

key

Return value

String "popped" value
Bool FALSE if set identified by key is empty or doesn't exist.

Example
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/
$redis->sPop('key1'); /* 'member1', 'key1' => {'member3', 'member2'} */
$redis->sPop('key1'); /* 'member3', 'key1' => {'member2'} */


sRandMember

Description

Returns a random element from the set value at Key, without removing it.

取得指定SET容器中的一个随机元素，但不会在SET容器中移除它。

Parameters

key

Return value

String value from the set
Bool FALSE if set identified by key is empty or doesn't exist.

Example
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/
$redis->sRandMember('key1'); /* 'member1', 'key1' => {'member3', 'member1', 'member2'} */
$redis->sRandMember('key1'); /* 'member3', 'key1' => {'member3', 'member1', 'member2'} */


sInter

Description

Returns the members of a set resulting from the intersection of all the sets held at the specified keys. If just a single key is specified, then this command produces the members of this set. If one of the keys is missing, FALSE is returned.

返回指定SETS集合的交集结果。如果只是指定了一个SET集合，那么返回该SET集合。如果在参数中有参数错误，那么则返回FLASE。

Parameters

key1, key2, keyN: keys identifying the different sets on which we will apply the intersection.

参数列表，代表不同的SET集合。

Return value

Array, contain the result of the intersection between those keys. If the intersection beteen the different sets is empty, the return value will be empty array.

返回数组，数组中的结果为所有SET集合的交集。如果所涉及到的SET集合没有交集结果，那么将返回一个空数组。

Examples
$redis->sAdd('key1', 'val1');
$redis->sAdd('key1', 'val2');
$redis->sAdd('key1', 'val3');
$redis->sAdd('key1', 'val4');

$redis->sAdd('key2', 'val3');
$redis->sAdd('key2', 'val4');

$redis->sAdd('key3', 'val3');
$redis->sAdd('key3', 'val4');

var_dump($redis->sInter('key1', 'key2', 'key3'));

Output:

array(2) {
  [0]=>
  string(4) "val4"
  [1]=>
  string(4) "val3"
}


sInterStore

Description

Performs a sInter command and stores the result in a new set.

执行一个交集操作，并把结果存储到一个新的SET容器中。

Parameters

Key: dstkey, the key to store the diff into.

key 储存结果的SET容器KEY

Keys: key1, key2... keyN. key1..keyN are intersected as in sInter.

求交集的KEYS

Return value

INTEGER: The cardinality of the resulting set, or FALSE in case of a missing key.

Example
$redis->sAdd('key1', 'val1');
$redis->sAdd('key1', 'val2');
$redis->sAdd('key1', 'val3');
$redis->sAdd('key1', 'val4');

$redis->sAdd('key2', 'val3');
$redis->sAdd('key2', 'val4');

$redis->sAdd('key3', 'val3');
$redis->sAdd('key3', 'val4');

var_dump($redis->sInterStore('output', 'key1', 'key2', 'key3'));
var_dump($redis->sMembers('output'));

Output:

int(2)

array(2) {
  [0]=>
  string(4) "val4"
  [1]=>
  string(4) "val3"
}


sUnion

Description

Performs the union between N sets and returns it.

执行一个并集操作在N个SET容器之间，并返回结果。

Parameters

Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis.

Return value

Array of strings: The union of all these sets.

返回一个数组

Example
$redis->delete('s0', 's1', 's2');

$redis->sAdd('s0', '1');
$redis->sAdd('s0', '2');
$redis->sAdd('s1', '3');
$redis->sAdd('s1', '1');
$redis->sAdd('s2', '3');
$redis->sAdd('s2', '4');

var_dump($redis->sUnion('s0', 's1', 's2'));

Return value: all elements that are either in s0 or in s1 or in s2.

array(4) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "1"
  [3]=>
  string(1) "2"
}


sUnionStore

Description

Performs the same action as sUnion, but stores the result in the first key

执行一个并集操作就和sUnion()一样，但是结果储存在第一个参数中。

Parameters

Key: dstkey, the key to store the diff into.

存储结果的SET集合KEY

Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis.

求并集的KEYS

Return value

INTEGER: The cardinality of the resulting set, or FALSE in case of a missing key.

返回整数值：并集结果的个数。

Example
$redis->delete('s0', 's1', 's2');

$redis->sAdd('s0', '1');
$redis->sAdd('s0', '2');
$redis->sAdd('s1', '3');
$redis->sAdd('s1', '1');
$redis->sAdd('s2', '3');
$redis->sAdd('s2', '4');

var_dump($redis->sUnionStore('dst', 's0', 's1', 's2'));
var_dump($redis->sMembers('dst'));

Return value: the number of elements that are either in s0 or in s1 or in s2.

int(4)
array(4) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "1"
  [3]=>
  string(1) "2"
}


sDiff

Description

Performs the difference between N sets and returns it.

执行差集操作在N个不同的SET容器之间，并返回结果。这个操作取得结果是第一个SET相对于其他参与计算的SET集合的差集。(Result = SET0 - (SET1 UNION SET2 UNION ....SET N))

Parameters

Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis.

Return value

Array of strings: The difference of the first set will all the others.

返回数组,返回的是第一个SET集合相对于其他集合的差集(first set - (N sets))

返回数组：第一个SET集合的补

Example
$redis->delete('s0', 's1', 's2');

$redis->sAdd('s0', '1');
$redis->sAdd('s0', '2');
$redis->sAdd('s0', '3');
$redis->sAdd('s0', '4');

$redis->sAdd('s1', '1');
$redis->sAdd('s2', '3');

var_dump($redis->sDiff('s0', 's1', 's2'));

Return value: all elements of s0 that are neither in s1 nor in s2.

array(2) {
  [0]=>
  string(1) "4"
  [1]=>
  string(1) "2"
}


sDiffStore

Description

Performs the same action as sDiff, but stores the result in the first key

与sDiff函数功能一直，只是结果为一个新的SET集合，存储到dstkey。

Parameters

Key: dstkey, the key to store the diff into.

Key:存储结果的SET集合KEY

Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis

参与操作的SET集合

Return value

INTEGER: The cardinality of the resulting set, or FALSE in case of a missing key.

返回整数：为结果集的个数。

Example
$redis->delete('s0', 's1', 's2');

$redis->sAdd('s0', '1');
$redis->sAdd('s0', '2');
$redis->sAdd('s0', '3');
$redis->sAdd('s0', '4');

$redis->sAdd('s1', '1');
$redis->sAdd('s2', '3');

var_dump($redis->sDiffStore('dst', 's0', 's1', 's2'));
var_dump($redis->sMembers('dst'));

Return value: the number of elements of s0 that are neither in s1 nor in s2.

int(2)
array(2) {
  [0]=>
  string(1) "4"
  [1]=>
  string(1) "2"
}


sMembers, sGetMembers

Description

Returns the contents of a set.

返回SET集合中的所有元素。

Parameters

Key: key

Return value

An array of elements, the contents of the set.

Example
$redis->delete('s');
$redis->sAdd('s', 'a');
$redis->sAdd('s', 'b');
$redis->sAdd('s', 'a');
$redis->sAdd('s', 'c');
var_dump($redis->sMembers('s'));

Output:

array(3) {
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "a"
  [2]=>
  string(1) "b"
}

The order is random and corresponds to redis' own internal representation of the set structure.

结果集的顺序是随机的，这也符合Redis本身对SET数据结构的定义。不重复，无顺序的集合。


zSet数据类型相关函数

ZSET(stored set)

和 set 一样是字符串的集合，不同的是每个元素都会关联一个 double 类型的 score 。实现使用的是skip list 和 hash table ， skip list 的实现使用的是双线链表。 Score 的主要作用是排序，因此sorted set 主要用作索引。


zAdd

Description

Adds the specified member with a given score to the sorted set stored at key.

增加一个或多个元素，如果该元素已经存在，更新它的socre值
虽然有序集合有序，但它也是集合，不能重复元素，添加重复元素只会
更新原有元素的score值

Parameters

key
score : double
value: string

Return value

Long 1 if the element is added. 0 otherwise.

Example
$redis->zAdd('key', 1, 'val1');
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 5, 'val5');
$redis->zRange('key', 0, -1); // array(val0, val1, val5)


zRange

Description

Returns a range of elements from the ordered set stored at the specified key, with values in the range [start, end]. start and stop are interpreted as zero-based indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ...

取得特定范围内的排序元素,0代表第一个元素,1代表第二个以此类推。-1代表最后一个,-2代表倒数第二个...

Parameters

key
start: long
end: long
withscores: bool = false

Return value

Array containing the values in specified range.

Example
$redis->zAdd('key1', 0, 'val0');
$redis->zAdd('key1', 2, 'val2');
$redis->zAdd('key1', 10, 'val10');
$redis->zRange('key1', 0, -1); /* array('val0', 'val2', 'val10') */

// with scores
$redis->zRange('key1', 0, -1, true); /* array('val0' => 0, 'val2' => 2, 'val10' => 10) */


zDelete, zRem

Description

Deletes a specified member from the ordered set.

从有序集合中删除指定的成员。

Parameters

key
member

Return value

LONG 1 on success, 0 on failure.

Example
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zDelete('key', 'val2');
$redis->zRange('key', 0, -1); /* array('val0', 'val10') */


zRevRange

Description

Returns the elements of the sorted set stored at the specified key in the range [start, end] in reverse order. start and stop are interpretated as zero-based indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ...

返回key对应的有序集合中指定区间的所有元素。这些元素按照score从高到低的顺序进行排列。对于具有相同的score的元素而言，将会按照递减的字典顺序进行排列。该命令与ZRANGE类似，只是该命令中元素的排列顺序与前者不同。

Parameters

key
start: long
end: long
withscores: bool = false

Return value

Array containing the values in specified range.

Example
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zRevRange('key', 0, -1); /* array('val10', 'val2', 'val0') */

// with scores
$redis->zRevRange('key', 0, -1, true); /* array('val10' => 10, 'val2' => 2, 'val0' => 0) */


zRangeByScore, zRevRangeByScore

Description

Returns the elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before start or end excludes it from the range. +inf and -inf are also valid limits. zRevRangeByScore returns the same items in reverse order, when the start and end parameters are swapped.

返回key对应的有序集合中score介于min和max之间的所有元素（包哈score等于min或者max的元素）。元素按照score从低到高的顺序排列。如果元素具有相同的score，那么会按照字典顺序排列。
可选的选项LIMIT可以用来获取一定范围内的匹配元素。如果偏移值较大，有序集合需要在获得将要返回的元素之前进行遍历，因此会增加O(N)的时间复杂度。可选的选项WITHSCORES可以使得在返回元素的同时返回元素的score，该选项自从Redis 2.0版本后可用。

Parameters

key
start: string
end: string
options: array

Two options are available: withscores => TRUE, and limit => array($offset, $count)

Return value

Array containing the values in specified range.

Example
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zRangeByScore('key', 0, 3); /* array('val0', 'val2') */
$redis->zRangeByScore('key', 0, 3, array('withscores' => TRUE); /* array('val0' => 0, 'val2' => 2) */
$redis->zRangeByScore('key', 0, 3, array('limit' => array(1, 1)); /* array('val2' => 2) */
$redis->zRangeByScore('key', 0, 3, array('limit' => array(1, 1)); /* array('val2') */
$redis->zRangeByScore('key', 0, 3, array('withscores' => TRUE, 'limit' => array(1, 1)); /* array('val2' => 2) */


zCount

Description

Returns the number of elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before start or end excludes it from the range. +inf and -inf are also valid limits.

返回key对应的有序集合中介于min和max间的元素的个数。

Parameters

key
start: string
end: string

Return value

LONG the size of a corresponding zRangeByScore.

Example
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zCount('key', 0, 3); /* 2, corresponding to array('val0', 'val2') */


zRemRangeByScore, zDeleteRangeByScore

Description

Deletes the elements of the sorted set stored at the specified key which have scores in the range [start,end].

移除key对应的有序集合中scroe位于min和max（包含端点）之间的所哟元素。从2.1.6版本后开始，区间端点min和max可以被排除在外，这和ZRANGEBYSCORE的语法一样。

Parameters

key
start: double or "+inf" or "-inf" string
end: double or "+inf" or "-inf" string

Return value

LONG The number of values deleted from the sorted set

Example
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zRemRangeByScore('key', 0, 3); /* 2 */


zRemByRank,zDeleteRangeByRank

zRemRangeByRank, zDeleteRangeByRank

Description

Deletes the elements of the sorted set stored at the specified key which have rank in the range [start,end].

移除key对应的有序集合中rank值介于start和stop之间的所有元素。start和stop均是从0开始的，并且两者均可以是负值。当索引值为负值时，表明偏移值从有序集合中score值最高的元素开始。例如：-1表示具有最高score的元素，而-2表示具有次高score的元素，以此类推。

Parameters

key
start: LONG
end: LONG

Return value

LONG The number of values deleted from the sorted set

Example
$redis->zAdd('key', 1, 'one');
$redis->zAdd('key', 2, 'two');
$redis->zAdd('key', 3, 'three');
$redis->zRemRangeByRank('key', 0, 1); /* 2 */
$redis->zRange('key', 0, -1, array('withscores' => TRUE)); /* array('three' => 3) */


zSize, zCard

Description

Returns the cardinality of an ordered set.

返回存储在key对应的有序集合中的元素的个数。

Parameters

key

Return value

Long, the set's cardinality

Example
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zSize('key'); /* 3 */


zScore

Description

Returns the score of a given member in the specified sorted set.

返回key对应的有序集合中member的score值。如果member在有序集合中不存在，那么将会返回nil。

Parameters

key
member

Return value

Double

Example
$redis->zAdd('key', 2.5, 'val2');
$redis->zScore('key', 'val2'); /* 2.5 */


zRank, zRevRank

Description

Returns the rank of a given member in the specified sorted set, starting at 0 for the item with the smallest score. zRevRank starts at 0 for the item with the largest score.

返回key对应的有序集合中member元素的索引值，元素按照score从低到高进行排列。rank值（或index）是从0开始的，这意味着具有最低score值的元素的rank值为0。使用ZREVRANK可以获得从高到低排列的元素的rank（或index）。

Parameters

key
member

Return value

Long, the item's score.

Example
$redis->delete('z');
$redis->zAdd('key', 1, 'one');
$redis->zAdd('key', 2, 'two');
$redis->zRank('key', 'one'); /* 0 */
$redis->zRank('key', 'two'); /* 1 */
$redis->zRevRank('key', 'one'); /* 1 */
$redis->zRevRank('key', 'two'); /* 0 */


zIncrBy

Description

Increments the score of a member from a sorted set by a given amount.

将key对应的有序集合中member元素的scroe加上increment。如果指定的member不存在，那么将会添加该元素，并且其score的初始值为increment。如果key不存在，那么将会创建一个新的有序列表，其中包含member这一唯一的元素。如果key对应的值不是有序列表，那么将会发生错误。指定的score的值应该是能够转换为数字值的字符串，并且接收双精度浮点数。同时，你也可用提供一个负值，这样将减少score的值。

Parameters

key
value: (double) value that will be added to the member's score
member

Return value

DOUBLE the new value

Examples
$redis->delete('key');
$redis->zIncrBy('key', 2.5, 'member1'); /* key or member1 didn't exist, so member1's score is to 0 before the increment */
                      /* and now has the value 2.5  */
$redis->zIncrBy('key', 1, 'member1'); /* 3.5 */


zUnion

Description

Creates an union of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument. The third optionnel argument defines weights to apply to the sorted sets in input. In this case, the weights will be multiplied by the score of each element in the sorted set before applying the aggregation. The forth argument defines the AGGREGATEoption which specify how the results of the union are aggregated.

对keys对应的numkeys个有序集合计算合集，并将结果存储在destination中。在传递输入keys之前必须提供输入keys的个数和其它可选参数。在默认情况下，元素的结果score是包含该元素的所有有序集合中score的和。如果使用WEIGHTS选项，你可以对每一个有序集合指定一个操作因子。这意味着每一个有序集合中的每个元素的score在传递给聚合函数之前均会被乘以该因子。当WEIGHTS没有指定时，操作因子默认为1。
使用AGGREGATE选项，你可以指定交集中的结果如何被聚合。该选项默认值为SUM，在这种情况下，一个元素的所有score值均会被相加。当选项被设置为MIN或MAX时，结果集合中将会包含一个元素的最大或者最小的score值。如果destination已经存在，那么它将会被重写。

Parameters

keyOutput
arrayZSetKeys
arrayWeights
aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zUnion.

Return value

LONG The number of values in the new sorted set.

Example
$redis->delete('k1');
$redis->delete('k2');
$redis->delete('k3');
$redis->delete('ko1');
$redis->delete('ko2');
$redis->delete('ko3');

$redis->zAdd('k1', 0, 'val0');
$redis->zAdd('k1', 1, 'val1');

$redis->zAdd('k2', 2, 'val2');
$redis->zAdd('k2', 3, 'val3');

$redis->zUnion('ko1', array('k1', 'k2')); /* 4, 'ko1' => array('val0', 'val1', 'val2', 'val3') */

/* Weighted zUnion */
$redis->zUnion('ko2', array('k1', 'k2'), array(1, 1)); /* 4, 'ko1' => array('val0', 'val1', 'val2', 'val3') */
$redis->zUnion('ko3', array('k1', 'k2'), array(5, 1)); /* 4, 'ko1' => array('val0', 'val2', 'val3', 'val1') */


zInter

Description

Creates an intersection of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument. The third optionnel argument defines weights to apply to the sorted sets in input. In this case, the weights will be multiplied by the score of each element in the sorted set before applying the aggregation. The forth argument defines the AGGREGATEoption which specify how the results of the union are aggregated.

计算numkeys个由keys指定的有序集合的交集，并且将结果存储在destination中。在该命令中，在你传递输入keys之前，必须提供输入keys的个数和其它可选的参数。
在默认情况下，一个元素的结果score是具有该元素的所有有序集合的score的和。关于WEIGHTS和AGGREGATE选项，可以参看ZUNIONSTORE命令。如果目标已经存在，那么它将会被重写。

Parameters

keyOutput
arrayZSetKeys
arrayWeights
aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zInter.

Return value

LONG The number of values in the new sorted set.

Example
$redis->delete('k1');
$redis->delete('k2');
$redis->delete('k3');

$redis->delete('ko1');
$redis->delete('ko2');
$redis->delete('ko3');
$redis->delete('ko4');

$redis->zAdd('k1', 0, 'val0');
$redis->zAdd('k1', 1, 'val1');
$redis->zAdd('k1', 3, 'val3');

$redis->zAdd('k2', 2, 'val1');
$redis->zAdd('k2', 3, 'val3');

$redis->zInter('ko1', array('k1', 'k2'));               /* 2, 'ko1' => array('val1', 'val3') */
$redis->zInter('ko2', array('k1', 'k2'), array(1, 1));  /* 2, 'ko2' => array('val1', 'val3') */

/* Weighted zInter */
$redis->zInter('ko3', array('k1', 'k2'), array(1, 5), 'min'); /* 2, 'ko3' => array('val1', 'val3') */
$redis->zInter('ko4', array('k1', 'k2'), array(1, 5), 'max'); /* 2, 'ko4' => array('val3', 'val1') */


Hash数据类型相关函数

 redis hash是一个string类型的field和value的映射表.它的添加，删除操作都是O(1)（平均）.hash特别适合用于存储对象。相较于将对象的每个字段存成单个string类型。将一个对象存储在hash类型中会占用更少的内存，并且可以更方便的存取整个对象。省内存的原因是新建一个hash对象时开始是用zipmap（又称为small hash）来存储的。这个zipmap其实并不是hash table，但是zipmap相比正常的hash实现可以节省不少hash本身需要的一些元数据存储开销。尽管zipmap的添加，删除，查找都是O(n)，但是由于一般对象的field数量都不太多。所以使用zipmap也是很快的,也就是说添加删除平均还是O(1)。


hSet

Description

Adds a value to the hash stored at key. If this value is already in the hash, FALSE is returned.

添加一个VALUE到HASH中。如果VALUE已经存在于HASH中，则返回FALSE。

Parameters

key
hashKey
value

Return value

LONG 1 if value didn't exist and was added successfully, 0 if the value was already present and was replaced, FALSE if there was an error.

Example
$redis->delete('h')
$redis->hSet('h', 'key1', 'hello'); /* 1, 'key1' => 'hello' in the hash at "h" */
$redis->hGet('h', 'key1'); /* returns "hello" */

$redis->hSet('h', 'key1', 'plop'); /* 0, value was replaced. */
$redis->hGet('h', 'key1'); /* returns "plop" */


hSetNx

Description

Adds a value to the hash stored at key only if this field isn't already in the hash.

添加一个VALUE到HASH STORE中，如果FIELD不存在。

Return value

BOOL TRUE if the field was set, FALSE if it was already present.

Example
$redis->delete('h')
$redis->hSetNx('h', 'key1', 'hello'); /* TRUE, 'key1' => 'hello' in the hash at "h" */
$redis->hSetNx('h', 'key1', 'world'); /* FALSE, 'key1' => 'hello' in the hash at "h". No change since the field wasn't replaced. */


hGet

Description

Gets a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, FALSE is returned.

取得HASH中的VALUE，如何HASH不存在，或者KEY不存在返回FLASE。

Parameters

key
hashKey

Return value

STRING The value, if the command executed successfully BOOL FALSE in case of failure


hLen

Description

Returns the length of a hash, in number of items

取得HASH表的长度。

Parameters

key

Return value

LONG the number of items in a hash, FALSE if the key doesn't exist or isn't a hash.

Example
$redis->delete('h')
$redis->hSet('h', 'key1', 'hello');
$redis->hSet('h', 'key2', 'plop');
$redis->hLen('h'); /* returns 2 */


hDel

Description

Removes a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, FALSE is returned.

删除指定的元素。

Parameters

key
hashKey

Return value

BOOL TRUE in case of success, FALSE in case of failure


hKeys

Description

Returns the keys in a hash, as an array of strings.

取得HASH表中的KEYS，以数组形式返回。

Parameters

Key: key

Return value

An array of elements, the keys of the hash. This works like PHP's array_keys().

Example
$redis->delete('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hKeys('h'));

Output:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
}

The order is random and corresponds to redis' own internal representation of the set structure.


hVals

Description

Returns the values in a hash, as an array of strings.

取得HASH表中所有的VALUE，以数组形式返回。

Parameters

Key: key

Return value

An array of elements, the values of the hash. This works like PHP's array_values().

Example
$redis->delete('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hVals('h'));

Output:

array(4) {
  [0]=>
  string(1) "x"
  [1]=>
  string(1) "y"
  [2]=>
  string(1) "z"
  [3]=>
  string(1) "t"
}

The order is random and corresponds to redis' own internal representation of the set structure.


hGetAll

Description

Returns the whole hash, as an array of strings indexed by strings.

取得整个HASH表的信息，返回一个以KEY为索引VALUE为内容的数组。

Parameters

Key: key

Return value

An array of elements, the contents of the hash.

Example
$redis->delete('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hGetAll('h'));

Output:

array(4) {
  ["a"]=>
  string(1) "x"
  ["b"]=>
  string(1) "y"
  ["c"]=>
  string(1) "z"
  ["d"]=>
  string(1) "t"
}

The order is random and corresponds to redis' own internal representation of the set structure.


hExists

Description

Verify if the specified member exists in a key.

验证HASH表中是否存在指定的KEY-VALUE

Parameters

key
memberKey

Return value

BOOL: If the member exists in the hash table, return TRUE, otherwise return FALSE.

Examples
$redis->hSet('h', 'a', 'x');
$redis->hExists('h', 'a'); /*  TRUE */
$redis->hExists('h', 'NonExistingKey'); /* FALSE */


hIncrBy

Description

Increments the value of a member from a hash by a given amount.

根据HASH表的KEY，为KEY对应的VALUE自增参数VALUE。

Parameters

key
member
value: (integer) value that will be added to the member's value

Return value

LONG the new value

Examples
$redis->delete('h');
$redis->hIncrBy('h', 'x', 2); /* returns 2: h[x] = 2 now. */
$redis->hIncrBy('h', 'x', 1); /* h[x] ← 2 + 1. Returns 3 */


hIncrByFloat

Description

Increments the value of a hash member by the provided float value

根据HASH表的KEY，为KEY对应的VALUE自增参数VALUE。浮点型
Parameters

key
member
value: (float) value that will be added to the member's value

Return value

FLOAT the new value

Examples
$redis->delete('h');
$redis->hIncrByFloat('h','x', 1.5); /* returns 1.5: h[x] = 1.5 now */
$redis->hIncrByFLoat('h', 'x', 1.5); /* returns 3.0: h[x] = 3.0 now */
$redis->hIncrByFloat('h', 'x', -3.0); /* returns 0.0: h[x] = 0.0 now */


hMset

Description

Fills in a whole hash. Non-string values are converted to string, using the standard (string) cast. NULL values are stored as empty strings.

批量填充HASH表。不是字符串类型的VALUE，自动转换成字符串类型。使用标准的值。NULL值将被储存为一个空的字符串。

Parameters

key
members: key → value array

Return value

BOOL

Examples
$redis->delete('user:1');
$redis->hMset('user:1', array('name' => 'Joe', 'salary' => 2000));
$redis->hIncrBy('user:1', 'salary', 100); // Joe earns 100 more now.


hMGet

Description

Retrieve the values associated to the specified fields in the hash.

批量取得HASH表中的VALUE。

Parameters

key
memberKeys Array

Return value

Array An array of elements, the values of the specified fields in the hash, with the hash keys as array keys.

Examples
$redis->delete('h');
$redis->hSet('h', 'field1', 'value1');
$redis->hSet('h', 'field2', 'value2');
$redis->hmGet('h', array('field1', 'field2')); /* returns array('field1' => 'value1', 'field2' => 'value2') */