phpredis中文开发文档
刚好要用看了网上翻译版本都是2011,2012年的,随手翻译一下新版
2017年10月28日23:48:08
使用方法 : Ctrl+F
官方英文版 https://github.com/phpredis/phpredis
makedown URL:https://github.com/phpredis/phpredis/blob/develop/README.markdown
- 安装/配置
- 安装
- 在OSX上安装
- 在Windows上构建
- PHP Session handler
- 分布式Redis阵列
2 类和方法
- 用法
- 连接
- 服务器
- Keys and strings
- Hashes
- Lists
- Sets
- Sorted sets
- Geocoding
- Pub/sub
- Transactions
- Scripting
- Introspection 自我检查
安装/配置
应该在你的系统上安装PhpRedis的一切。
安装扩展
phpize
./configure [--enable-redis-igbinary]
make && make install
如果您希望phpredis使用igbinary库序列化数据,请使用--enable-redis-igbinary运行configure。 将安装副本redis.so安装到适当的位置,但您仍然需要在PHP配置文件中启用该模块。 为此,请编辑您的php.ini或在/etc/php5/conf.d中添加一个redis.ini文件,其中包含以下内容:extension = redis.so。
您可以通过运行./mkdeb-apache2.sh或使用dpkg-buildpackage或svn-buildpackage生成PHP5的debian软件包,可从Apache 2访问。
此扩展导出一个类Redis(和RedisException用于出现错误时)。 请查看https://github.com/ukko/phpredis-phpdoc以获取您可以在IDE中用于代码完成的PHP存根。
在OSX上安装
如果OSX上的安装失败,请在再次尝试以前在shell中键入以下命令:
MACOSX_DEPLOYMENT_TARGET=10.6
CFLAGS="-arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp"
CCFLAGS="-arch i386 -arch x86_64 -g -Os -pipe"
CXXFLAGS="-arch i386 -arch x86_64 -g -Os -pipe"
LDFLAGS="-arch i386 -arch x86_64 -bind_at_load"
export CFLAGS CXXFLAGS LDFLAGS CCFLAGS MACOSX_DEPLOYMENT_TARGET
如果仍然失败,并且您正在运行Zend Server CE,请在“make”之前尝试:./configure CFLAGS =“ - arch i386”。
取自Zend Server CE / OSX上的phpredis编译。
另请参阅:使用Macports安装Redis和PHP扩展程序PHPRedis。
您可以使用Homebrew进行安装:
获得homebrew-php
brew安装php55-redis(或php53-redis,php54-redis)
PHP Session handler
phpredis可以用来存储PHP会话。 要执行此操作,请在php.ini中配置session.save_handler和session.save_path以告知phpredis在哪里存储会话:
session.save_handler = redis
session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2&read_timeout=2.5"
session.save_path也可以有一个简单的主机:端口格式,但是如果要使用参数,则需要提供tcp://方案。以下参数可用:
- weight(integer):主机的权重与其他主机相比较,以便在几个主机上自定义会话分发。如果主机A的主机B的重量是两倍,则会占到会话数量的两倍。在该示例中,host1存储所有会话的20%(1 /(1 + 2 + 2)),而host2和host3每个存储40%(2/1 + 2 + 2)。目标主机在会话开始时一劳永逸地确定,不会改变。默认权重为1。
- timeout(float):连接超时到redis主机,以秒为单位。如果主机在那段时间内无法访问,会话存储将不可用于客户端。默认超时非常高(86400秒)。
- persistent(integer,应为1或0):定义是否应使用持久连接。 (实验设定)
- 前缀(字符串,默认为“PHPREDIS_SESSION:”):用作存储会话的Redis密钥的前缀。密钥由前缀后跟会话ID组成。
- auth(字符串,默认为空):用于在发送命令之前与服务器进行身份验证。
- database(integer):选择不同的数据库。
会话具有以秒为单位的生命周期,并存储在INI变量“session.gc_maxlifetime”中。 您可以使用ini_set()更改它。 会话处理程序需要使用SETEX命令的Redis版本(至少为2.0)。 phpredis也可以连接到unix域套接字:session.save_path =“unix:///var/run/redis/redis.sock?persistent = 1&weight = 1&database = 0。
- 在Windows上构建
请参阅@ char101关于如何在Windows上构建phpredis的说明。
分布式Redis阵列
See dedicated page. 参看中文翻译版 http://www.cnblogs.com/zx-admin/p/7750609.html
Redis Cluster支持
See dedicated page. 参看中文翻译版 http://www.cnblogs.com/zx-admin/p/7750612.html
运行单元测试
phpredis使用一个小的定制单元测试套件来测试各种类的功能。 要运行测试,只需执行以下操作:
# 运行Redis类的测试(注意这是默认值)
php tests/TestRedis.php --class Redis
# 运行RedisArray类的测试
tests/mkring.sh start
php tests/TestRedis.php --class RedisArray
tests/mkring.sh stop
# 运行RedisCluster类的测试
tests/make-cluster.sh start
php tests/TestRedis.php --class RedisCluster
tests/make-cluster.sh stop
请注意,可以通过在调用时传递附加参数“-test”,仅运行与测试本身的子串相匹配的测试。
# Just run the 'echo' test
php tests/TestRedis.php --class Redis --test echo
类和方法
用法
- Redis类
- RedisException类
- 预定义常数
Redis类
说明:创建一个Redis客户端
例:
$redis = new Redis();
RedisException类
如果无法到达Redis服务器,phpredis将抛出一个RedisException对象。 如果连接问题,如果Redis服务关闭,或者redis主机超载,则可能会发生这种情况。 在不涉及不可达服务器(如密钥不存在,无效命令等)的任何其他问题的情况下,phpredis将返回FALSE。
预定义常量
说明:可用的Redis常数
Redis数据类型,按类型返回
Redis::REDIS_STRING - String
Redis::REDIS_SET - Set
Redis::REDIS_LIST - List
Redis::REDIS_ZSET - Sorted set
Redis::REDIS_HASH - Hash
Redis::REDIS_NOT_FOUND - Not found / other
@TODO: OPT_SERIALIZER, AFTER, BEFORE,...
连接
- connect, open - 打开 - 连接到服务器
- pconnect, popen - popen - 连接到服务器(持久)
- auth -验证服务器
- select -更改当前连接的选定数据库
- close - 关闭连接
- setOption - 设置客户端选项
- getOption - 获取客户端选项
- ping - ping服务器
- echo - 回应给定的字符串
connect, open
说明:连接到Redis实例
参数
host: string。 可以是一个主机,或者到unix域的路径套接字端口:int,可选的超时:float,以秒为单位的值(可选,默认为0意思无限制)保留:如果指定retry_interval,则应为NULL retry_interval:int,以毫秒为单位的值 (可选)read_timeout:float,以秒为单位的值(可选,默认为0表示无限制)
返回值
BOOL:TRUE成功,FALSE错误。
例
$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.
$redis->connect('127.0.0.1', 6379, 1, NULL, 100); // 1 sec timeout, 100ms delay between reconnection attempts.
pconnect, popen
说明:连接到Redis实例或重新使用已经使用pconnect / popen建立的连接。
在php进程结束之前,连接将不会在关闭或结束请求时关闭。 因此,在连接到一个redis服务器的许多服务器上使用持久连接时,请耐心打开FD(特别是redis服务器端)。
还可以通过host + port + timeout或host + persistent_id或unix socket + timeout来标识多个持久连接。
此功能在当前版本中不可用。 pconnect和popen然后工作像他们的非持久性一样。
参数
主机:字符串。 可以是主机,或者到unix域的路径socket端口:int,可选timeout:float,以秒为单位的值(可选,默认为0表示无限制)persistent_id:string。 请求的持久连接的身份retry_interval:int,以毫秒为单位的值(可选)read_timeout:float,以秒为单位的值(可选,默认为0表示无限制)
返回值
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 than the three before.
$redis->pconnect('/tmp/redis.sock'); // unix domain socket - would be another connection than the four before.
账号认证
说明:使用密码验证连接。 警告:密码通过网络以纯文本格式发送。
参数
STRING: password
返回值
BOOL: TRUE
if the connection is authenticated, FALSE
otherwise.
Example
$redis->auth('foobared');
select
说明:更改当前连接的选定数据库。
参数
INTEGER: dbindex, 要切换到的数据库号
返回值
TRUE
in case of success, FALSE
in case of failure.
例
参见方法例如:move
close
说明:断开与Redis实例的连接,但使用pconnect时除外。
setOption
说明:设置客户端选项。
参数
参数名称,参数值
返回值
BOOL: TRUE
on success, FALSE
on error.
例
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // 不要序列化数据
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); // 使用内置的serialize / unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // 使用igBinary serialize / unserialize
$redis->setOption(Redis::OPT_PREFIX, 'myAppName:'); // 在所有键上使用自定义前缀
/*
SCAN系列命令的选项,指示是否抽象
来自用户的空白结果。 如果设置为SCAN_NORETRY(默认),phpredis
一次只会发出一个SCAN命令,有时候返回一个空
数组结果。 如果设置为SCAN_RETRY,phpredis将重试扫描命令
直到键返回或Redis返回一个零的迭代器
*/
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY);
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
getOption
说明:获取客户端选项。
参数
parameter name
返回值
Parameter value.
例
$redis->getOption(Redis::OPT_SERIALIZER); // return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, or Redis::SERIALIZER_IGBINARY.
ping
说明:检查当前的连接状态
参数
(none)
Return value
STRING:+ PONG成功。 如上所述,在连接错误时抛出RedisException对象。
echo
说明:发送一个字符串到Redis,它用相同的字符串回复
参数
STRING: The message to send.
返回值
STRING: the same message.
Server
- bgRewriteAOF - 异步重写仅追加文件
- bgSave - 将数据集异步保存到磁盘(在后台)
- config - 获取或设置Redis服务器配置参数
- dbSize - 返回所选数据库中的键数
- flushAll - 从所有数据库中删除所有密钥
- flushDb - 从当前数据库中删除所有密钥
- info - 获取有关服务器的信息和统计信息
- lastSave - 获取最后一个磁盘保存的时间戳
- resetStat - 重置由info方法返回的统计信息。
- save - 同步将数据集保存到磁盘(等待完成)
- slaveOf - 使服务器成为另一个实例的奴隶,或者将其提升为主
- time - 返回当前服务器的时间
- slowLog - 访问Redis slowLog条目
bgRewriteAOF
说明:启动AOF(仅追加文件)的背景重写
参数
None.
返回值
BOOL: TRUE
in case of success, FALSE
in case of failure.
例
$redis->bgRewriteAOF();
bgSave
说明:异步将数据集保存到磁盘(在后台)
参数
None.
返回值
BOOL: TRUE
in case of success, FALSE
in case of failure. 如果保存已经运行,则此命令将失败并返回FALSE。
例
$redis->bgSave();
config
说明:获取或设置Redis服务器配置参数。
参数
操作(字符串)GET的SET或SET键字符串,GET的glob-pattern。 有关示例,请参阅http://redis.io/commands/config-get。 值可选字符串(仅适用于SET)
返回值
Associative array for GET
, key -> value bool for SET
例
$redis->config("GET", "*max-*-entries*");
$redis->config("SET", "dir", "/var/run/redis/dumps/");
dbSize
说明:返回所选数据库中的键数
参数
None.
返回值
INTEGER: DB size, in number of keys.
例
$count = $redis->dbSize();
echo "Redis has $count keys\n";
flushAll
说明:从所有数据库中删除所有密钥
参数
None.
返回值
BOOL: Always TRUE
.
例
$redis->flushAll();
flushDb
Description: Remove all keys from the current database.
Parameters
None.
Return value
BOOL: Always TRUE
.
Example
$redis->flushDb();
info
Description: Get information and statistics about the server
Returns an associative array 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_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 */
lastSave
Description: Returns the timestamp of the last disk save.
Parameters
None.
Return value
INT: timestamp.
Example
$redis->lastSave();
resetStat
Description: Reset the stats returned by info method.
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();
save
Description: Synchronously save the dataset to disk (wait to complete)
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();
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();
time
Description: Return the current server time.
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();
slowLog
Description: Access the Redis slowLog
Parameters
Operation (string): This can be either GET
, LEN
, or RESET
Length (integer), optional: If executing a SLOWLOG GET
command, you can pass an optional length.
Return value
The return value of SLOWLOG will depend on which operation was performed. SLOWLOG GET: Array of slowLog entries, as provided by Redis SLOGLOG LEN: Integer, the length of the slowLog SLOWLOG RESET: Boolean, depending on success
Examples
// Get ten slowLog entries
$redis->slowLog('get', 10);
// Get the default number of slowLog entries
$redis->slowLog('get');
// Reset our slowLog
$redis->slowLog('reset');
// Retrieve slowLog length
$redis->slowLog('len');
Keys and Strings
Strings
- append - Append a value to a key
- bitCount - Count set bits in a string
- bitOp - Perform bitwise operations between strings
- decr, decrBy - Decrement the value of a key
- get - Get the value of a key
- getBit - Returns the bit value at offset in the string value stored at key
- getRange - Get a substring of the string stored at a key
- getSet - Set the string value of a key and return its old value
- incr, incrBy - Increment the value of a key
- incrByFloat - Increment the float value of a key by the given amount
- mGet, getMultiple - Get the values of all the given keys
- mSet, mSetNX - Set multiple keys to multiple values
- set - Set the string value of a key
- setBit - Sets or clears the bit at offset in the string value stored at key
- setEx, pSetEx - Set the value and expiration of a key
- setNx - Set the value of a key, only if the key does not exist
- setRange - Overwrite part of a string at key starting at the specified offset
- strLen - Get the length of the value stored in a key
Keys
- del, delete - Delete a key
- dump - Return a serialized version of the value stored at the specified key.
- exists - Determine if a key exists
- expire, setTimeout, pexpire - Set a key's time to live in seconds
- expireAt, pexpireAt - Set the expiration for a key as a UNIX timestamp
- keys, getKeys - Find all keys matching the given pattern
- scan - Scan for keys in the keyspace (Redis >= 2.8.0)
- migrate - Atomically transfer a key from a Redis instance to another one
- move - Move a key to another database
- object - Inspect the internals of Redis objects
- persist - Remove the expiration from a key
- randomKey - Return a random key from the keyspace
- rename, renameKey - Rename a key
- renameNx - Rename a key, only if the new key does not exist
- type - Determine the type stored at key
- sort - Sort the elements in a list, set or sorted set
- ttl, pttl - Get the time to live for a key
- restore - Create a key using the provided serialized value, previously obtained with dump.
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.
Examples
$redis->get('key');
set
Description: Set the string value in argument as value of the key. If you're using Redis >= 2.6.12, you can pass extended options as explained below
Parameters
Key Value Timeout or Options Array (optional). If you pass an integer, phpredis will redirect to SETEX, and will try to use Redis >= 2.6.12 extended options if you pass an array with valid values
Return value
Bool TRUE
if the command is successful.
Examples
// Simple key -> value set
$redis->set('key', 'value');
// Will redirect, and actually make an SETEX call
$redis->set('key','value', 10);
// Will set the key, if it doesn't exist, with a ttl of 10 seconds
$redis->set('key', 'value', Array('nx', 'ex'=>10));
// Will set a key, if it does exist, with a ttl of 1000 miliseconds
$redis->set('key', 'value', Array('xx', 'px'=>1000));
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.
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.
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.
Parameters
An array of keys, or an undefined number of parameters, each a key: key1 key2 key3 ... keyN
Return value
Long Number of keys deleted.
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 */
exists
Description: Verify if the specified key exists.
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.
Parameters
key value: value that will be added to key (only for incrBy)
Return value
INT the new value
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); /* 4 */
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.
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.
Parameters
Array: Array containing the list of the keys
Return value
Array: Array containing the values related to keys in argument
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`, 'value1', `FALSE`);
getSet
Description: Sets a value and returns the previous entry at that key.
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'
randomKey
Description: Returns a random key.
Parameters
None.
Return value
STRING: an existing key in redis.
Example
$key = $redis->randomKey();
$surprise = $redis->get($key); // who knows what's in there.
move
Description: Moves a key to a different database.
Parameters
Key: key, the key to move.
INTEGER: dbindex, the database number to move the key to.
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.
Parameters
STRING: srckey, the key to rename.
STRING: dstkey, the new name for the 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.
expire, setTimeout, pexpire
Description: Sets an expiration date (a timeout) on an item. pexpire requires a TTL in milliseconds.
Parameters
Key: key. The key that will disappear.
Integer: ttl. The key's remaining Time To Live, in seconds.
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.
Parameters
Key: key. The key that will disappear.
Integer: Unix timestamp. The key's date of death, in seconds from Epoch time.
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.
Parameters
STRING: pattern, using '*' as a wildcard.
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*');
scan
Description: Scan the keyspace for keys
Parameters
LONG (reference): Iterator, initialized to NULL STRING, Optional: Pattern to match LONG, Optional: Count of keys per iteration (only a suggestion to Redis)
Return value
Array, boolean: This function will return an array of keys or FALSE if Redis returned zero keys
Example
/* Without enabling Redis::SCAN_RETRY (default condition) */
$it = NULL;
do {
// Scan for some keys
$arr_keys = $redis->scan($it);
// Redis may return empty results, so protect against that
if ($arr_keys !== FALSE) {
foreach($arr_keys as $str_key) {
echo "Here is a key: $str_key\n";
}
}
} while ($it > 0);
echo "No more keys to scan!\n";
/* With Redis::SCAN_RETRY enabled */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
$it = NULL;
/* phpredis will retry the SCAN command if empty results are returned from the
server, so no empty results check is required. */
while ($arr_keys = $redis->scan($it)) {
foreach ($arr_keys as $str_key) {
echo "Here is a key: $str_key\n";
}
}
echo "No more keys to scan!\n";
object
Description: Describes the object pointed to by a 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).
type
Description: Returns the type of data pointed by a given key.
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');
append
Description: Append specified string to the string stored in specified key.
Parameters
Key Value
Return value
INTEGER: Size of the value after the append
Example
$redis->set('key', 'value1');
$redis->append('key', 'value2'); /* 12 */
$redis->get('key'); /* 'value1value2' */
getRange
Description: Return a substring of a larger string
Note: substr also supported but deprecated in redis.
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.
sort
Description: Sort the elements in a list, set or sorted set.
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
ttl, pttl
Description: Returns the time to live left for a given key in seconds (ttl), or milliseconds (pttl).
Parameters
Key: key
Return value
LONG: The time to live in seconds. If the key has no ttl, -1
will be returned, and -2
if the key doesn't exist.
Example
$redis->ttl('key');
persist
Description: Remove the expiration timer from a 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.
Example
$redis->persist('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).
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"
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.
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.
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.
Note:: Redis introduced migrating multiple keys in 3.0.6, so you must have at least that version in order to call migrate
with an array of keys.
Parameters
host string. The destination host
port integer. The TCP port to connect to.
key(s) string or array.
destination-db integer. The target DB.
timeout integer. The maximum amount of time given to this transfer.
copy boolean, optional. Should we send the COPY flag to redis.
replace boolean, optional. Should we send the REPLACE flag to redis
Examples
$redis->migrate('backup', 6379, 'foo', 0, 3600);
$redis->migrate('backup', 6379, 'foo', 0, 3600, true, true); /* copy and replace */
$redis->migrate('backup', 6379, 'foo', 0, 3600, false, true); /* just REPLACE flag */
/* Migrate multiple keys (requires Redis >= 3.0.6)
$redis->migrate('backup', 6379, ['key1', 'key2', 'key3'], 0, 3600);
Hashes
- hDel - Delete one or more hash fields
- hExists - Determine if a hash field exists
- hGet - Get the value of a hash field
- hGetAll - Get all the fields and values in a hash
- hIncrBy - Increment the integer value of a hash field by the given number
- hIncrByFloat - Increment the float value of a hash field by the given amount
- hKeys - Get all the fields in a hash
- hLen - Get the number of fields in a hash
- hMGet - Get the values of all the given hash fields
- hMSet - Set multiple hash fields to multiple values
- hSet - Set the string value of a hash field
- hSetNx - Set the value of a hash field, only if the field does not exist
- hVals - Get all the values in a hash
- hScan - Scan a hash key for members
- hStrLen - Get the string length of the value associated with field in the hash
hSet
Description: Adds a value to the hash stored at key.
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.
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.
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
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 hashKey1 hashKey2 ...
Return value
LONG the number of deleted keys, 0 if the key doesn't exist, FALSE
if the key isn't a hash.
hKeys
Description: Returns the keys in a hash, as an array of strings.
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.
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.
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.
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.
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
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.
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.
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') */
hScan
Description: Scan a HASH value for members, with an optional pattern and count
Parameters
key: String iterator: Long (reference) pattern: Optional pattern to match against count: How many keys to return in a go (only a sugestion to Redis)
Return value
Array An array of members that match our pattern
Examples
$it = NULL;
/* Don't ever return an empty array until we're done iterating */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
while($arr_keys = $redis->hScan('hash', $it)) {
foreach($arr_keys as $str_field => $str_value) {
echo "$str_field => $str_value\n"; /* Print the hash member and value */
}
}
hStrLen
Description: Get the string length of the value associated with field in the hash stored at key.
Parameters
key: String field: String
Return value
LONG the string length of the value associated with field, or zero when field is not present in the hash or key does not exist at all.
Lists
- blPop, brPop - Remove and get the first/last element in a list
- bRPopLPush - Pop a value from a list, push it to another list and return it
- lIndex, lGet - Get an element from a list by its index
- lInsert - Insert an element before or after another element in a list
- lLen, lSize - Get the length/size of a list
- lPop - Remove and get the first element in a list
- lPush - Prepend one or multiple values to a list
- lPushx - Prepend a value to a list, only if the list exists
- lRange, lGetRange - Get a range of elements from a list
- lRem, lRemove - Remove elements from a list
- lSet - Set the value of an element in a list by its index
- lTrim, listTrim - Trim a list to the specified range
- rPop - Remove and get the last element in a list
- rPopLPush - Remove the last element in a list, append it to another list and return it (redis >= 1.1)
- rPush - Append one or multiple values to a list
- rPushX - Append a value to a list, only if the list exists
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. If 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.
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*/
bRPopLPush
Description: A blocking version of rPopLPush
, with an integral timeout in the third parameter.
Parameters
Key: srckey Key: dstkey Long: timeout
Return value
STRING The element that was moved in case of success, FALSE
in case of timeout.
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.
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` */
/
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.
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 */
lPop
Description: Return and remove the first element of the list.
Parameters
key
Return value
STRING if command executed successfully BOOL FALSE
in case of failure (empty list)
Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->lPop('key1'); /* key1 => [ 'B', 'C' ] */
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.
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.
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' ] */
lPushx
Description: Adds the string value to the head (left) of the list if the list exists.
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.
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' ] */
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') */
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.
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') */
lSet
Description: Set the list at index with the new value.
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.
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' */
lTrim, listTrim
Description: Trims an existing list so that it will contain only a specified range of elements.
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') */
rPop
Description: Returns and removes the last element of the list.
Parameters
key
Return value
STRING if command executed successfully BOOL FALSE
in case of failure (empty list)
Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->rPop('key1'); /* key1 => [ 'A', 'B' ] */
rPopLPush
Description: Pops a value from the tail of a list, and pushes it to the front of another list. Also return this value. (redis >= 1.1)
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"
}
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.
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.
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' ] */
rPushX
Description: Adds the string value to the tail (right) of the list if the ist exists. FALSE
in case of Failure.
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.
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' ] */
lLen, 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
.
Parameters
Key
Return value
LONG The size of the list identified by Key exists. BOOL FALSE
if the data type identified by Key is not list
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 */
Sets
- sAdd - Add one or more members to a set
- sCard, sSize - Get the number of members in a set
- sDiff - Subtract multiple sets
- sDiffStore - Subtract multiple sets and store the resulting set in a key
- sInter - Intersect multiple sets
- sInterStore - Intersect multiple sets and store the resulting set in a key
- sIsMember, sContains - Determine if a given value is a member of a set
- sMembers, sGetMembers - Get all the members in a set
- sMove - Move a member from one set to another
- sPop - Remove and return one or more members of a set at random
- sRandMember - Get one or multiple random members from a set
- sRem, sRemove - Remove one or more members from a set
- sUnion - Add multiple sets
- sUnionStore - Add multiple sets and store the resulting set in a key
- sScan - Scan a set for members
sAdd
Description: Adds a value to the set value stored at key. If this value is already in the set, FALSE
is returned.
Parameters
key value
Return value
LONG the number of elements added to the set.
Example
$redis->sAdd('key1' , 'member1'); /* 1, 'key1' => {'member1'} */
$redis->sAdd('key1' , 'member2', 'member3'); /* 2, 'key1' => {'member1', 'member2', 'member3'}*/
$redis->sAdd('key1' , 'member2'); /* 0, 'key1' => {'member1', 'member2', 'member3'}*/
sCard, sSize
Description: Returns the cardinality of the set identified by key.
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 */
sDiff
Description: Performs the difference between N sets and returns it.
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.
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
Parameters
Key: dstkey, the key to store the diff into.
Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis
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"
}
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.
Parameters
key1, key2, keyN: keys identifying the different sets on which we will apply the intersection.
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.
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.
Parameters
Key: dstkey, the key to store the diff into.
Keys: key1, key2... keyN. key1..keyN are intersected as in sInter.
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"
}
sIsMember, sContains
Description: Checks if value
is a member of the set stored at the key key
.
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 */
sMembers, sGetMembers
Description: Returns the contents of a 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.
sMove
Description: Moves the specified member from the set at srcKey to the set at dstKey.
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.
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'} */
sPop
Description: Removes and returns a random element from the set value at Key.
Parameters
key count: Integer, optional
Return value (without count argument)
String "popped" value Bool FALSE
if set identified by key is empty or doesn't exist.
Return value (with count argument)
Array: Member(s) returned or an empty array if the set doesn't exist Bool: FALSE
on error if the key is not a set
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'} */
/* With count */
$redis->sAdd('key2', 'member1', 'member2', 'member3');
$redis->sPop('key2', 3); /* Will return all members but in no particular order */
sRandMember
Description: Returns a random element from the set value at Key, without removing it.
Parameters
key count (Integer, optional)
Return value
If no count is provided, a random String value from the set will be returned. If a count is provided, an array of values from the set will be returned. Read about the different ways to use the count here: SRANDMEMBER 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'}*/
// No count
$redis->sRandMember('key1'); /* 'member1', 'key1' => {'member3', 'member1', 'member2'} */
$redis->sRandMember('key1'); /* 'member3', 'key1' => {'member3', 'member1', 'member2'} */
// With a count
$redis->sRandMember('key1', 3); // Will return an array with all members from the set
$redis->sRandMember('key1', 2); // Will an array with 2 members of the set
$redis->sRandMember('key1', -100); // Will return an array of 100 elements, picked from our set (with dups)
$redis->sRandMember('empty-set', 100); // Will return an empty array
$redis->sRandMember('not-a-set', 100); // Will return FALSE
sRem, sRemove
Description: Removes the specified member from the set value stored at key.
Parameters
key member
Return value
LONG The number of elements removed from the set.
Example
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/
$redis->sRem('key1', 'member2', 'member3'); /*return 2. 'key1' => {'member1'} */
sUnion
Description: Performs the union between N sets and returns it.
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
Parameters
Key: dstkey, the key to store the diff into.
Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis.
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"
}
sScan
Description: Scan a set for members
Parameters
Key: The set to search iterator: LONG (reference) to the iterator as we go pattern: String, optional pattern to match againstcount: How many members to return at a time (Redis might return a different amount)
Return value
Array, boolean: PHPRedis will return an array of keys or FALSE when we're done iterating
Example
$it = NULL;
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); /* don't return empty results until we're done */
while($arr_mems = $redis->sScan('set', $it, "*pattern*")) {
foreach($arr_mems as $str_mem) {
echo "Member: $str_mem\n";
}
}
$it = NULL;
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY); /* return after each iteration, even if empty */
while(($arr_mems = $redis->sScan('set', $it, "*pattern*"))!==FALSE) {
if(count($arr_mems) > 0) {
foreach($arr_mems as $str_mem) {
echo "Member found: $str_mem\n";
}
} else {
echo "No members in this iteration, iterator value: $it\n";
}
}
Sorted sets
- zAdd - Add one or more members to a sorted set or update its score if it already exists
- zCard, zSize - Get the number of members in a sorted set
- zCount - Count the members in a sorted set with scores within the given values
- zIncrBy - Increment the score of a member in a sorted set
- zInter - Intersect multiple sorted sets and store the resulting sorted set in a new key
- zRange - Return a range of members in a sorted set, by index
- zRangeByScore, zRevRangeByScore - Return a range of members in a sorted set, by score
- zRangeByLex - Return a lexigraphical range from members that share the same score
- zRank, zRevRank - Determine the index of a member in a sorted set
- zRem, zDelete - Remove one or more members from a sorted set
- zRemRangeByRank, zDeleteRangeByRank - Remove all members in a sorted set within the given indexes
- zRemRangeByScore, zDeleteRangeByScore - Remove all members in a sorted set within the given scores
- zRevRange - Return a range of members in a sorted set, by index, with scores ordered from high to low
- zScore - Get the score associated with the given member in a sorted set
- zUnion - Add multiple sorted sets and store the resulting sorted set in a new key
- zScan - Scan a sorted set for members
zAdd
Description: Add one or more members to a sorted set or update its score if it already exists
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)
zCard, zSize
Description: Returns the cardinality of an ordered set.
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 */
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.
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') */
zIncrBy
Description: Increments the score of a member from a sorted set by a given amount.
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 */
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 AGGREGATE
option which specify how the results of the union are aggregated.
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') */
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 ...
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) */
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.
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') */
$redis->zRangeByScore('key', 0, 3, array('withscores' => TRUE, 'limit' => array(1, 1)); /* array('val2' => 2) */
zRangeByLex
Description: Returns a lexigraphical range of members in a sorted set, assuming the members have the same score. The min and max values are required to start with '(' (exclusive), '[' (inclusive), or be exactly the values '-' (negative inf) or '+' (positive inf). The command must be called with either three or five arguments or will return FALSE.
Parameters
key: The ZSET you wish to run against min: The minimum alphanumeric value you wish to get max: The maximum alphanumeric value you wish to get offset: Optional argument if you wish to start somewhere other than the first element.limit: Optional argument if you wish to limit the number of elements returned.
Return value
Array containing the values in the specified range.
Example
foreach(Array('a','b','c','d','e','f','g') as $c)
$redis->zAdd('key',0,$c);
$redis->zRangeByLex('key','-','[c') /* Array('a','b','c'); */
$redis->zRangeByLex('key','-','(c') /* Array('a','b') */
$redis->zRangeByLex('key','-','[c',1,2) /* Array('b','c') */
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.
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 */
zRem, zDelete
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') */
zRemRangeByRank, zDeleteRangeByRank
Description: Deletes the elements of the sorted set stored at the specified key which have rank in the range [start,end].
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) */
zRemRangeByScore, zDeleteRangeByScore
Description: Deletes the elements of the sorted set stored at the specified key which have scores in the range [start,end].
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 */
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 ...
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) */
zScore
Description: Returns the score of a given member in the specified sorted set.
Parameters
key member
Return value
Double
Example
$redis->zAdd('key', 2.5, 'val2');
$redis->zScore('key', 'val2'); /* 2.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 AGGREGATE
option which specify how the results of the union are aggregated.
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, 'ko2' => array('val0', 'val1', 'val2', 'val3') */
$redis->zUnion('ko3', array('k1', 'k2'), array(5, 1)); /* 4, 'ko3' => array('val0', 'val2', 'val3', 'val1') */
zScan
Description: Scan a sorted set for members, with optional pattern and count
Parameters
key: String, the set to scan iterator: Long (reference), initialized to NULL pattern: String (optional), the pattern to match count: How many keys to return per iteration (Redis might return a different number)
Return value
Array, boolean PHPRedis will return matching keys from Redis, or FALSE when iteration is complete
Example
$it = NULL;
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
while($arr_matches = $redis->zScan('zset', $it, '*pattern*')) {
foreach($arr_matches as $str_mem => $f_score) {
echo "Key: $str_mem, Score: $f_score\n";
}
}
Geocoding
geoAdd
Prototype
$redis->geoAdd($key, $longitude, $latitude, $member [, $longitude, $lattitude, $member, ...]);
Description: Add one or more geospacial items to the specified key. This function must be called with at least one longitude, latitude, member triplet.
Return value
Integer: The number of elements added to the geospacial key.
Example
$redis->del("myplaces");
/* Since the key will be new, $result will be 2 */
$result = $redis->geoAdd(
"myplaces",
37.773, -122.431, "San Francisco",
-157.858, 21.315, "Honolulu"
);
geoHash
Prototype
$redis->geoHash($key, $member [, $member, $member, ...]);
Description: Retreive Geohash strings for one or more elements of a geospacial index.
Return value
Array: One or more Redis Geohash encoded strings.
Example
$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui");
$hashes = $redis->geoHash("hawaii", "Honolulu", "Maui");
var_dump($hashes);
Output
array(2) {
[0]=>
string(11) "87z9pyek3y0"
[1]=>
string(11) "8e8y6d5jps0"
}
geoPos
Prototype
$redis->geoPos($key, $member [, $member, $member, ...]);
Description: Return longitude, lattitude positions for each requested member.
Return value
Array: One or more longitude/latitude positions
Example
$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui");
$positions = $redis->geoPos("hawaii", "Honolulu", "Maui");
var_dump($positions);
Output
array(2) {
[0]=>
array(2) {
[0]=>
string(22) "-157.85800248384475708"
[1]=>
string(19) "21.3060004581273077"
}
[1]=>
array(2) {
[0]=>
string(22) "-156.33099943399429321"
[1]=>
string(20) "20.79799924753607598"
}
}
GeoDist
Prototype
$redis->geoDist($key, $member1, $member2 [, $unit]);
Description: Return the distance between two members in a geospacial set. If units are passed it must be one of the following values:
- 'm' => Meters
- 'km' => Kilometers
- 'mi' => Miles
- 'ft' => Feet
Return value
Double: The distance between the two passed members in the units requested (meters by default).
Example
$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui");
$meters = $redis->geoDist("hawaii", "Honolulu", "Maui");
$kilometers = $redis->geoDist("hawaii", "Honolulu", "Maui", 'km');
$miles = $redis->geoDist("hawaii", "Honolulu", "Maui", 'mi');
$feet = $redis->geoDist("hawaii", "Honolulu", "Maui", 'ft');
echo "Distance between Honolulu and Maui:\n";
echo " meters : $meters\n";
echo " kilometers: $kilometers\n";
echo " miles : $miles\n";
echo " feet : $feet\n";
/* Bad unit */
$inches = $redis->geoDist("hawaii", "Honolulu", "Maui", 'in');
echo "Invalid unit returned:\n";
var_dump($inches);
Output
Distance between Honolulu and Maui:
meters : 168275.204
kilometers: 168.2752
miles : 104.5616
feet : 552084.0028
Invalid unit returned:
bool(false)
geoRadius
Prototype
$redis->geoRadius($key, $longitude, $latitude, $radius, $unit [, Array $options]);
Description: Return members of a set with geospacial information that are within the radius specified by the caller.
Options Array
The georadius command can be called with various options that control how Redis returns results. The following table describes the options phpredis supports. All options are case insensitive.
Key | Value | Description |
---|---|---|
COUNT | integer > 0 | Limit how many results are returned |
WITHCOORD | Return longitude and latitude of matching members | |
WITHDIST | Return the distance from the center | |
WITHHASH | Return the raw geohash-encoded score | |
ASC | Sort results in ascending order | |
DESC | Sort results in descending order |
Note: It doesn't make sense to pass both ASC
and DESC
options but if both are passed the last one passed will win!
Note: PhpRedis does not currently support the STORE
or STOREDIST
options but will be added to future versions.
Return value
Array: Zero or more entries that are within the provided radius.
Example
/* Add some cities */
$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui");
echo "Within 300 miles of Honolulu:\n";
var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi'));
echo "\nWithin 300 miles of Honolulu with distances:\n";
$options = ['WITHDIST'];
var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options));
echo "\nFirst result within 300 miles of Honolulu with distances:\n";
$options['count'] = 1;
var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options));
echo "\nFirst result within 300 miles of Honolulu with distances in descending sort order:\n";
$options[] = 'DESC';
var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options));
Output
Within 300 miles of Honolulu:
array(2) {
[0]=>
string(8) "Honolulu"
[1]=>
string(4) "Maui"
}
Within 300 miles of Honolulu with distances:
array(2) {
[0]=>
array(2) {
[0]=>
string(8) "Honolulu"
[1]=>
string(6) "0.0002"
}
[1]=>
array(2) {
[0]=>
string(4) "Maui"
[1]=>
string(8) "104.5615"
}
}
First result within 300 miles of Honolulu with distances:
array(1) {
[0]=>
array(2) {
[0]=>
string(8) "Honolulu"
[1]=>
string(6) "0.0002"
}
}
First result within 300 miles of Honolulu with distances in descending sort order:
array(1) {
[0]=>
array(2) {
[0]=>
string(4) "Maui"
[1]=>
string(8) "104.5615"
}
}
geoRadiusByMember
Prototype
$redis->geoRadiusByMember($key, $member, $radius, $units [, Array $options]);
Description: This method is identical to geoRadius except that instead of passing a longitude and latitude as the "source" you pass an existing member in the geospacial set.
Options Array
See geoRadius command for options array.
Return value
Array: The zero or more entries that are close enough to the member given the distance and radius specified.
Example
$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui");
echo "Within 300 miles of Honolulu:\n";
var_dump($redis->geoRadiusByMember("hawaii", "Honolulu", 300, 'mi'));
echo "\nFirst match within 300 miles of Honolulu:\n";
var_dump($redis->geoRadiusByMember("hawaii", "Honolulu", 300, 'mi', Array('count' => 1)));
Output
Within 300 miles of Honolulu:
array(2) {
[0]=>
string(8) "Honolulu"
[1]=>
string(4) "Maui"
}
First match within 300 miles of Honolulu:
array(1) {
[0]=>
string(8) "Honolulu"
}
Pub/sub
- pSubscribe - Subscribe to channels by pattern
- publish - Post a message to a channel
- subscribe - Subscribe to channels
- pubSub - Introspection into the pub/sub subsystem
pSubscribe
Description: Subscribe to channels by pattern
Parameters
patterns: An array of patterns to match
callback: Either a string or an array with an object and method. The callback will get four arguments ($redis, $pattern, $channel, $message)
return value: Mixed. Any non-null return value in the callback will be returned to the caller.
Example
function pSubscribe($redis, $pattern, $chan, $msg) {
echo "Pattern: $pattern\n";
echo "Channel: $chan\n";
echo "Payload: $msg\n";
}
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.
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. return value: Mixed. Any non-null return value in the callback will be returned to the caller.
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
pubSub
Description: A command allowing you to get information on the Redis pub/sub system.
Parameters
keyword: String, which can be: "channels", "numsub", or "numpat" argument: Optional, variant. For the "channels" subcommand, you can pass a string pattern. For "numsub" an array of channel names.
Return value
CHANNELS: Returns an array where the members are the matching channels. NUMSUB: Returns a key/value array where the keys are channel names and values are their counts. NUMPAT: Integer return containing the number active pattern subscriptions
Example
$redis->pubSub("channels"); /*All channels */
$redis->pubSub("channels", "*pattern*"); /* Just channels matching your pattern */
$redis->pubSub("numsub", Array("chan1", "chan2")); /*Get subscriber counts for 'chan1' and 'chan2'*/
$redis->pubSub("numpat"); /* Get the number of pattern subscribers */
Generic
- rawCommand - Execute any generic command against the server.
rawCommand
Description: A method to execute any arbitrary command against the a Redis server
Parameters
This method is variadic and takes a dynamic number of arguments of various types (string, long, double), but must be passed at least one argument (the command keyword itself).
Return value
The return value can be various types depending on what the server itself returns. No post processing is done to the returned value and must be handled by the client code.
Example
/* Returns: true */
$redis->rawCommand("set", "foo", "bar"); /* Returns: "bar" */
$redis->rawCommand("get", "foo"); /* Returns: 3 */
$redis->rawCommand("rpush", "mylist", "one", 2, 3.5)); /* Returns: ["one", "2", "3.5000000000000000"] */
$redis->rawCommand("lrange", "mylist", 0, -1);
Transactions
- multi, exec, discard - Enter and exit transactional mode
- watch, unwatch - Watches a key for modifications by another client.
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. discard
cancels a transaction.
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.
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.
Parameters
keys: string for one key or array for a list of keys
Example
$redis->watch('x'); // or for a list of keys: $redis->watch(array('x','another key'));
/* 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.
*/
Scripting
- eval - Evaluate a LUA script serverside
- evalSha - Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself
- script - Execute the Redis SCRIPT command to perform various operations on the scripting subsystem
- getLastError - The last error message (if any)
- clearLastError - Clear the last error message
- _prefix - A utility method to prefix the value with the prefix setting for phpredis
- _unserialize - A utility method to unserialize data with whatever serializer is set up
- _serialize - A utility method to serialize data with whatever serializer is set up
eval
Description: Evaluate a LUA script serverside
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).
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.
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
client
Description: Issue the CLIENT command with various arguments.
The Redis CLIENT command can be used in four ways.
- CLIENT LIST
- CLIENT GETNAME
- CLIENT SETNAME [name]
- CLIENT KILL [ip:port]
Usage
$redis->client('list'); // Get a list of clients
$redis->client('getname'); // Get the name of the current connection
$redis->client('setname', 'somename'); // Set the name of the current connection
$redis->client('kill', <ip:port>); // Kill the process at ip:port
Return value
This will vary depending on which client command was executed.
- CLIENT LIST will return an array of arrays with client information.
- CLIENT GETNAME will return the client name or false if none has been set
- CLIENT SETNAME will return true if it can be set and false if not
- CLIENT KILL will return true if the client can be killed, and false if not
Note: phpredis will attempt to reconnect so you can actually kill your own connection but may not notice losing it!
getLastError
Description: The last error message (if any)
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 '-'"
clearLastError
Description: Clear the last error message
Parameters
none
Return value
BOOL TRUE
Examples
$redis->set('x', 'a');
$redis->incr('x');
$err = $redis->getLastError();
// "ERR value is not an integer or out of range"
$redis->clearLastError();
$err = $redis->getLastError();
// NULL
_prefix
Description: A utility method to prefix the value with the prefix setting for phpredis.
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->setOption(Redis::OPT_PREFIX, 'my-prefix:');
$redis->_prefix('my-value'); // Will return 'my-prefix:my-value'
_serialize
Description: A utility method to serialize values manually.
This method allows you to serialize a value with whatever serializer is configured, manually. This can be useful for serialization/unserialization of data going in and out of EVAL commands as phpredis can't automatically do this itself. Note that if no serializer is set, phpredis will change Array values to 'Array', and Objects to 'Object'.
Parameters
value: Mixed. The value to be serialized
Examples
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE);
$redis->_serialize("foo"); // returns "foo"
$redis->_serialize(Array()); // Returns "Array"
$redis->_serialize(new stdClass()); // Returns "Object"
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
$redis->_serialize("foo"); // Returns 's:3:"foo";'
_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.
Parameters
value string. The value to be unserialized
Examples
$redis->setOption(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)
Introspection
isConnected
Description: A method to determine if a phpredis object thinks it's connected to a server
Parameters
None
Return value
Boolean Returns TRUE if phpredis thinks it's connected and FALSE if not
getHost
Description: Retreive our host or unix socket that we're connected to
Parameters
None
Return value
Mixed The host or unix socket we're connected to or FALSE if we're not connected
getPort
Description: Get the port we're connected to
Parameters
None
Return value
Mixed Returns the port we're connected to or FALSE if we're not connected
getDbNum
Description: Get the database number phpredis is pointed to
Parameters
None
Return value
Mixed Returns the database number (LONG) phpredis thinks it's pointing to or FALSE if we're not connected
getTimeout
Description: Get the (write) timeout in use for phpredis
Parameters
None
Return value
Mixed The timeout (DOUBLE) specified in our connect call or FALSE if we're not connected
getReadTimeout
Description: Get the read timeout specified to phpredis or FALSE if we're not connected
Parameters
None
Return value
Mixed Returns the read timeout (which can be set using setOption and Redis::OPT_READ_TIMEOUT) or FALSE if we're not connected
getPersistentID
Description: Gets the persistent ID that phpredis is using
Parameters
None
Return value
Mixed Returns the persistent id phpredis is using (which will only be set if connected with pconnect), NULL if we're not using a persistent ID, and FALSE if we're not connected
getAuth
Description: Get the password used to authenticate the phpredis connection
Parameters
None
Return value
Mixed Returns the password used to authenticate a phpredis session or NULL if none was used, and FALSE if we're not connected
phpredis中文开发文档的更多相关文章
- 在线API,桌面版,jquery,css,Android中文开发文档,JScript,SQL掌用实例
学习帮助文档大全 jquery,css,Android中文开发文档,JScript,SQL掌用实例 http://api.jq-school.com/
- jssip中文开发文档(完整版)
jsSip开发文档 (官网地址:http://www.jssip.net/) 完整案例demo下载地址: http://download.csdn.net/download/qq_39421580/1 ...
- sweetalert api中文开发文档和手册
官网和下载地址: http://t4t5.github.io/sweetalert/ 2016年10月30日14:10:21 废话,目前php开发越来越API话,所以php方法很多都是json返回数 ...
- (网页)sweetalert api 中文开发文档和手册,项目放弃alert
弹框json的特别好使. sweetalert 示例 基本信息弹窗swal("这是一条信息!") 标题与文本的信息弹窗swal("这是一条信息!", " ...
- uploadify中文开发文档,解决php多图上传
图片上传好用插件有,比如 uploadify ueditor html5的各种ajax上传插件,大部分都是异步,返回只是true之类,有些时候需要上传图片需要一起上传,其实可以通过操作流程来避免这个 ...
- 若快打码平台python开发文档修改版
一.打码的作用 在进行爬虫过程中,部分网站的登录验证码是比较简单的,例如四个英文数字随机组合而成的验证码,有的是全数字随机组成的验证码,有的是全中文随机组成的验证码.为了爬虫进行自动化,需要解决自动登 ...
- .NET6使用DOCFX自动生成开发文档
本文内容来自我写的开源电子书<WoW C#>,现在正在编写中,可以去WOW-Csharp/学习路径总结.md at master · sogeisetsu/WOW-Csharp (gith ...
- [翻译]开发文档:android Bitmap的高效使用
内容概述 本文内容来自开发文档"Traning > Displaying Bitmaps Efficiently",包括大尺寸Bitmap的高效加载,图片的异步加载和数据缓存 ...
- Net通用进销存管理系统 + 开发文档+ 使用说明
通用进销存管理系统 + 开发文档+ 使用说明Net源码下载 包括下面的模块基础资料模块采购管理模块库存管理模块商务管理模块营业管理模块维修管理模块会员管理模块财务管理模块 Net通用进销存管理系统 + ...
随机推荐
- PowerShe 消息提示框测试
1. 使用powerShell 弹出一个简单的消息框,代码如下,创建test.ps1脚本文件. $ConfirmPreference = 'None' $ws = New-Object -ComObj ...
- Xcode真机调试失败:The identity used to sign the executable is no longer valid
在Xcode中突然好久没有使用真机调试了.今天使用真机的时候.出现例如以下的警告.并真机执行失败: The identity used to sign the executable is no lon ...
- redmine在linux上的mysql性能优化方法与问题排查方案
iredmine的linux服务器mysql性能优化方法与问题排查方案 问题定位: 客户端工具: 1. 浏览器inspect-tool的network timing工具分析 2. 浏览 ...
- Software Engineer Title Ladder
http://changelog.ca/log/2013/08/09/software_engineer_title_ladder Within the software engineering pr ...
- 【原创 深度学习与TensorFlow 动手实践系列 - 1】第一课:深度学习总体介绍
最近一直在研究机器学习,看过两本机器学习的书,然后又看到深度学习,对深度学习产生了浓厚的兴趣,希望短时间内可以做到深度学习的入门和实践,因此写一个深度学习系列吧,通过实践来掌握<深度学习> ...
- RapidJson 的使用
rapidjson为了最大化性能,大量使用了浅拷贝,使用之前一定要了解清楚.如果采用了浅拷贝,特别要注意局部对象的使用,以防止对象已被析构了,却还在被使用. rapidjson使用注意点: 1.对不存 ...
- Asp.Net Nuget常用命令
1.安装 Install-Package EntityFramework //ef Install-Package EntityFramework.zh-Hans //ef中文
- Mina简单的入门示例
Mina是Apache下的一个网络应用程序框架,用来帮助用户简单地开发高性能和高可扩展性的网络应用程序.它提供了一个通过Java NIO在不同的传输协议上抽象的事件驱动的异步API,例如TCP/IP和 ...
- 链接学习之obj文件探索
Windows的gcc环境,往官网http://sourceforge.net/project/showfiles.php?group_id=2435 下载MinGW,安装,安装完毕后按照包 配置环境 ...
- spring MVC配置详解(转)
现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不过 ...