PHP-redis英文文档

Posted 盘古开地

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP-redis英文文档相关的知识,希望对你有一定的参考价值。

作为程序员,看英文文档是必备技能,所以尽量还是多看英文版的^^

phpRedis

The phpredis extension provides an API for communicating with the Redis key-value store. It is released under the PHP License, version 3.01. This code has been developed and maintained by Owlient from November 2009 to March 2011.

You can send comments, patches, questions here on github, to [email protected] (@yowgi), or to[email protected] (@grumi78).

Table of contents


  1. Installing/Configuring
  2. Classes and methods

Installing/Configuring


Everything you should need to install PhpRedis on your system.

Installation

phpize
./configure [--enable-redis-igbinary]
make && make install

If you would like phpredis to serialize your data using the igbinary library, run configure with --enable-redis-igbinarymake install copies redis.so to an appropriate location, but you still need to enable the module in the PHP config file. To do so, either edit your php.ini or add a redis.ini file in /etc/php5/conf.d with the following contents: extension=redis.so.

You can generate a debian package for PHP5, accessible from Apache 2 by running ./mkdeb-apache2.sh or with dpkg-buildpackage or svn-buildpackage.

This extension exports a single class, Redis (and RedisException used in case of errors). Check outhttps://github.com/ukko/phpredis-phpdoc for a PHP stub that you can use in your IDE for code completion.

Installation on OSX

If the install fails on OSX, type the following commands in your shell before trying again:

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

If that still fails and you are running Zend Server CE, try this right before "make": ./configure CFLAGS="-arch i386".

Taken from Compiling phpredis on Zend Server CE/OSX .

See also: Install Redis & PHP Extension PHPRedis with Macports.

You can install install it using Homebrew:

PHP Session handler

phpredis can be used to store PHP sessions. To do this, configure session.save_handler and session.save_path in your php.ini to tell phpredis where to store the sessions:

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"

session.save_path can have a simple host:port format too, but you need to provide the tcp:// scheme if you want to use the parameters. The following parameters are available:

  • weight (integer): the weight of a host is used in comparison with the others in order to customize the session distribution on several hosts. If host A has twice the weight of host B, it will get twice the amount of sessions. In the example, host1 stores 20% of all the sessions (1/(1+2+2)) while host2 and host3 each store 40% (2/1+2+2). The target host is determined once and for all at the start of the session, and doesn‘t change. The default weight is 1.
  • timeout (float): the connection timeout to a redis host, expressed in seconds. If the host is unreachable in that amount of time, the session storage will be unavailable for the client. The default timeout is very high (86400 seconds).
  • persistent (integer, should be 1 or 0): defines if a persistent connection should be used. (experimental setting)
  • prefix (string, defaults to "PHPREDIS_SESSION:"): used as a prefix to the Redis key in which the session is stored. The key is composed of the prefix followed by the session ID.
  • auth (string, empty by default): used to authenticate with the server prior to sending commands.
  • database (integer): selects a different database.

Sessions have a lifetime expressed in seconds and stored in the INI variable "session.gc_maxlifetime". You can change it withini_set(). The session handler requires a version of Redis with the SETEX command (at least 2.0). phpredis can also connect to a unix domain socket: session.save_path = "unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0.

Building on Windows

See instructions from @char101 on how to build phpredis on Windows.

Distributed Redis Array

See dedicated page.

Redis Cluster support

See dedicated page.

Running the unit tests

phpredis uses a small custom unit test suite for testing functionality of the various classes. To run tests, simply do the following:

# Run tests for Redis class (note this is the default)
php tests/TestRedis.php --class Redis

# Run tests for RedisArray class
tests/mkring.sh start
php tests/TestRedis.php --class RedisArray
tests/mkring.sh stop

# Run tests for the RedisCluster class
tests/make-cluster.sh start
php tests/TestRedis.php --class RedisCluster
tests/make-cluster.sh stop

Note that it is possible to run only tests which match a substring of the test itself by passing the additional argument ‘--test ‘ when invoking.

# Just run the ‘echo‘ test
php tests/TestRedis.php --class Redis --test echo

Classes and methods


Usage

  1. Class Redis
  2. Class RedisException
  3. Predefined constants

Class Redis


Description: Creates a Redis client

Example
$redis = new Redis();

Class RedisException


phpredis throws a RedisException object if it can‘t reach the Redis server. That can happen in case of connectivity issues, if the Redis service is down, or if the redis host is overloaded. In any other problematic case that does not involve an unreachable server (such as a key not existing, an invalid command, etc), phpredis will return FALSE.

Predefined constants


Description: Available Redis Constants

Redis data types, as returned by type

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

Connection

  1. connect, open - Connect to a server
  2. pconnect, popen - Connect to a server (persistent)
  3. auth - Authenticate to the server
  4. select - Change the selected database for the current connection
  5. close - Close the connection
  6. setOption - Set client option
  7. getOption - Get client option
  8. ping - Ping the server
  9. echo - Echo the given string

connect, open


Description: Connects to a Redis instance.

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) reserved: should be NULL if retry_interval is specified retry_interval: int, value in milliseconds (optional)

Return value

BOOLTRUE 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.
$redis->connect(‘127.0.0.1‘, 6379, 1, NULL, 100); // 1 sec timeout, 100ms delay between reconnection attempts.

pconnect, popen


Description: Connects to a Redis instance or reuse a connection already established with pconnect/popen.

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.

Also more than one persistent connection can be made identified by either host + port + timeout or host + persistent_id or unix socket + timeout.

This feature is not available in threaded versions. pconnect and popen then working like their non persistent equivalents.

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 retry_interval: int, value in milliseconds (optional)

Return value

BOOLTRUE 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.

auth


Description: Authenticate the connection using a password. Warning: The password is sent in plain-text over the network.

Parameters

STRING: password

Return value

BOOLTRUE if the connection is authenticated, FALSE otherwise.

Example
$redis->auth(‘foobared‘);

select


Description: Change the selected database for the current connection.

Parameters

INTEGER: dbindex, the database number to switch to.

Return value

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

Example

See method for example: move

close


Description: Disconnects from the Redis instance, except when pconnect is used.

setOption


Description: Set client option.

Parameters

parameter name parameter value

Return value

BOOLTRUE 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

/* Options for the SCAN family of commands, indicating whether to abstract
   empty results from the user.  If set to SCAN_NORETRY (the default), phpredis
   will just issue one SCAN command at a time, sometimes returning an empty
   array of results.  If set to SCAN_RETRY, phpredis will retry the scan command
   until keys come back OR Redis returns an iterator of zero
*/
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY);
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);

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.

echo


Description: Sends a string to Redis, which replies with the same string

Parameters

STRING: The message to send.

Return value

STRING: the same message.

Server

  1. bgRewriteAOF - Asynchronously rewrite the append-only file
  2. bgSave - Asynchronously save the dataset to disk (in background)
  3. config - Get or Set the Redis server configuration parameters
  4. dbSize - Return the number of keys in selected database
  5. flushAll - Remove all keys from all databases
  6. flushDb - Remove all keys from the current database
  7. info - Get information and statistics about the server
  8. lastSave - Get the timestamp of the last disk save
  9. resetStat - Reset the stats returned by info method.
  10. save - Synchronously save the dataset to disk (wait to complete)
  11. slaveOf - Make the server a slave of another instance, or promote it to master
  12. time - Return the current server time
  13. slowLog - Access the Redis slowLog entries

bgRewriteAOF


Description: Start the background rewrite of AOF (Append-Only File)

Parameters

None.

Return value

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

Example
$redis->bgRewriteAOF();

bgSave


Description: Asynchronously save the dataset to disk (in background)

Parameters

None.

Return value

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

config


Description: Get or Set the Redis server configuration parameters.

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/");

dbSize


Description: Return the number of keys in selected database.

Parameters

None.

Return value

INTEGER: DB size, in number of keys.

Example
$count = $redis->dbSize();
echo "Redis has $count keys\n";

flushAll


Description: Remove all keys from all databases.

Parameters

None.

Return value

BOOL: Always TRUE.

Example
$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

BOOLTRUE 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

BOOLTRUE 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

BOOLTRUE 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 GETLEN, 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

BOOLTRUE 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

BOOLTRUE 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

B

以上是关于PHP-redis英文文档的主要内容,如果未能解决你的问题,请参考以下文章

PHP-redis中文文档

php-redis中文文档

PHP-redis中文文档

在Mac上为XAMPP安装PHP-Redis

如何使用官方 PHP Docker 镜像方法安装 php-redis 扩展?

PHP-redis中文文档介绍(转自http://www.jb51.net/article/33887.htm)