workerman-redis

Introduction

workerman/redis is an asynchronous Redis component based on workerman.

Note
The main purpose of this project is to implement Redis asynchronous subscription (subscribe, pSubscribe).
Since Redis is fast enough, you do not need to use this asynchronous client unless you require psubscribe or subscribe for asynchronous subscription. Using the Redis extension would yield better performance.

Installation:

composer require workerman/redis ^v2.0.3

Callback Usage

use Workerman\Worker;
use Workerman\Redis\Client;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('http://0.0.0.0:6161');

$worker->onWorkerStart = function() {
    global $redis;
    $redis = new Client('redis://127.0.0.1:6379');
};

$worker->onMessage = function(TcpConnection $connection, $data) {
    global $redis;
    $redis->set('key', 'hello world');    
    $redis->get('key', function ($result) use ($connection) {
        $connection->send($result);
    });  
};

Worker::runAll();

Coroutine Usage

Note
Coroutine usage requires workerman>=5.0, workerman/redis>=2.0.0 and install composer require revolt/event-loop ^1.0.0

use Workerman\Worker;
use Workerman\Redis\Client;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('http://0.0.0.0:6161');

$worker->onWorkerStart = function() {
    global $redis;
    $redis = new Client('redis://127.0.0.1:6379');
};

$worker->onMessage = function(TcpConnection $connection, $data) {
    global $redis;
    $redis->set('key', 'hello world');    
    $result = $redis->get('key');
    $connection->send($result);
};

Worker::runAll();

When no callback function is set, the client will return asynchronous request results synchronously, and the request process does not block the current process, which means requests can be processed concurrently.

Note
psubscribe and subscribe do not support coroutine usage.

Documentation

Description

In callback mode, the callback function usually has 2 parameters ($result, $redis), where $result is the result and $redis is the redis instance. For example:

use Workerman\Redis\Client;
$redis = new Client('redis://127.0.0.1:6379');
// Set callback function to determine the result of set call
$redis->set('key', 'value', function ($result, $redis) {
    var_dump($result); // true
});
// Callback functions are optional parameters; here the callback function is omitted
$redis->set('key1', 'value1');
// Callback functions can be nested
$redis->get('key', function ($result, $redis){
    $redis->set('key2', 'value2', function ($result) {
        var_dump($result);
    });
});

Connection

use Workerman\Redis\Client;
// Omit callback
$redis = new Client('redis://127.0.0.1:6379');
// With callback
$redis = new Client('redis://127.0.0.1:6379', [
    'connect_timeout' => 10 // Set connection timeout of 10 seconds, defaults to 5 seconds if not set
], function ($success, $redis) {
    // Connection result callback
    if (!$success) echo $redis->error();
});

auth

// Password authentication
$redis->auth('password', function ($result) {

});
// Username and password authentication
$redis->auth('username', 'password', function ($result) {

});

pSubscribe

Subscribe to one or more channels that match the given pattern.

Each pattern uses * as a wildcard, for example, it* matches all channels that start with it (it.news, it.blog, it.tweets, etc.). news.* matches all channels that start with news. (news.it, news.global.today, etc.), and so on.

Note: The pSubscribe callback function has 4 parameters ($pattern, $channel, $message, $redis)

When the $redis instance calls the pSubscribe or subscribe interface, any subsequent method calls on the current instance will be ignored.

$redis = new Client('redis://127.0.0.1:6379');
$redis2 = new Client('redis://127.0.0.1:6379');
$redis->psubscribe(['news*', 'blog*'], function ($pattern, $channel, $message) {
    echo "$pattern, $channel, $message"; // news*, news.add, news content
});

Timer::add(5, function () use ($redis2){
    $redis2->publish('news.add', 'news content');
});

subscribe

Used to subscribe to information from one or more specified channels.

Note: The subscribe callback function has 3 parameters ($channel, $message, $redis)

When the $redis instance calls the pSubscribe or subscribe interface, any subsequent method calls on the current instance will be ignored.

$redis = new Client('redis://127.0.0.1:6379');
$redis2 = new Client('redis://127.0.0.1:6379');
$redis->subscribe(['news', 'blog'], function ($channel, $message) {
    echo "$channel, $message"; // news, news content
});

Timer::add(5, function () use ($redis2){
    $redis2->publish('news', 'news content');
});

publish

Used to send a message to the specified channel.

Returns the number of subscribers that received the message.

$redis2->publish('news', 'news content');

select

// Omit callback
$redis->select(2);
$redis->select('test', function ($result, $redis) {
    // The select parameter must be a number, so here $result will be false
    var_dump($result, $redis->error());
});

get

The command is used to get the value of the specified key. If the key does not exist, it returns NULL. If the value stored in the key is not of string type, it returns false.

$redis->get('key', function($result) {
     // If the key does not exist, it returns NULL; on error, it returns false
    var_dump($result);
});

set

Used to set the value of the given key. If the key already stores another value, SET will overwrite the old value, ignoring the type.

$redis->set('key', 'value');
$redis->set('key', 'value', function($result){});
// The third parameter can pass an expiration time; expires in 10 seconds
$redis->set('key','value', 10);
$redis->set('key','value', 10, function($result){});

setEx, pSetEx

Set the value and expiration time for the specified key. If the key already exists, the SETEX command will replace the old value.

// Note the second parameter specifies the expiration time in seconds
$redis->setEx('key', 3600, 'value'); 
// pSetEx uses milliseconds
$redis->pSetEx('key', 3600, 'value'); 

del

Used to delete existing keys, returning a number that represents how many keys were deleted (non-existing keys are not counted).

// Delete one key
$redis->del('key');
// Delete multiple keys
$redis->del(['key', 'key1', 'key2']);

setNx

(SETifNot eXists) command sets the specified value for the key if the key does not exist.

$redis->del('key');
$redis->setNx('key', 'value', function($result){
    var_dump($result); // 1
});
$redis->setNx('key', 'value', function($result){
    var_dump($result); // 0
});

exists

The command is used to check whether the given key exists. The return result is a number representing the count of existing keys.

$redis->set('key', 'value');
$redis->exists('key', function ($result) {
    var_dump($result); // 1
}); 
$redis->exists('NonExistingKey', function ($result) {
    var_dump($result); // 0
}); 

$redis->mset(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz']);
$redis->exists(['foo', 'bar', 'baz'], function ($result) {
    var_dump($result); // 3
}); 

incr, incrBy

Increment the numeric value stored in the key by one/a specified value. If the key does not exist, the value of the key will be initialized to 0 before performing the incr/incrBy operation.
If the value contains an erroneous type or the string type cannot be represented as a number, then it returns false.
On success, it returns the incremented value.

$redis->incr('key1', function ($result) {
    var_dump($result);
}); 
$redis->incrBy('key1', 10, function ($result) {
    var_dump($result);
}); 

incrByFloat

Add the specified floating-point increment to the value stored in the key.
If the key does not exist, INCRBYFLOAT will first set the value of the key to 0 before performing the addition operation.
If the value contains an erroneous type or the string type cannot be represented as a number, then it returns false.
On success, it returns the incremented value.

$redis->incrByFloat('key1', 1.5, function ($result) {
    var_dump($result);
}); 

decr, decrBy

The command decrements the value stored in the key by one/a specified decrement value.
If the key does not exist, the value of the key will be initialized to 0 before performing the decr/decrBy operation.
If the value contains an erroneous type or the string type cannot be represented as a number, then it returns false.
On success, it returns the decremented value.

$redis->decr('key1', function ($result) {
    var_dump($result);
}); 
$redis->decrBy('key1', 10, function ($result) {
    var_dump($result);
}); 

mGet

Returns the values of all (one or more) specified keys. If any of the specified keys do not exist, that key returns NULL.

$redis->set('key1', 'value1');
$redis->set('key2', 'value2');
$redis->set('key3', 'value3');
$redis->mGet(['key0', 'key1', 'key5'], function ($result) {
    var_dump($result); // [null, 'value1', null];
}); 

getSet

Used to set the value of the specified key and return the old value of the key.

$redis->set('x', '42');
$redis->getSet('x', 'lol', function ($result) {
    var_dump($result); // '42'
}) ;
$redis->get('x', function ($result) {
    var_dump($result); // 'lol'
}) ;

randomKey

Randomly returns a key from the current database.

$redis->randomKey(function($key) use ($redis) {
    $redis->get($key, function ($result) {
        var_dump($result); 
    }) ;
})

move

Move the key from the current database to the given database db.

$redis->select(0);  // switch to DB 0
$redis->set('x', '42'); // write 42 to x
$redis->move('x', 1, function ($result) {   // move to DB 1
    var_dump($result); // 1
}) ;  
$redis->select(1);  // switch to DB 1
$redis->get('x', function ($result) {
    var_dump($result); // '42'
}) ;

rename

Change the name of the key; returns false if the key does not exist.

$redis->set('x', '42');
$redis->rename('x', 'y', function ($result) {
    var_dump($result); // true
}) ;

renameNx

Rename the key when the new key does not exist.

$redis->del('y');
$redis->set('x', '42');
$redis->renameNx('x', 'y', function ($result) {
    var_dump($result); // 1
}) ;

expire

Set an expiration time for the key; the key will no longer be available after expiration. The unit is in seconds. Returns 1 on success, returns 0 if the key does not exist, and returns false on error.

$redis->set('x', '42');
$redis->expire('x', 3);

keys

The command is used to find all keys that match the given pattern.

$redis->keys('*', function ($keys) {
    var_dump($keys); 
}) ;
$redis->keys('user*', function ($keys) {
    var_dump($keys); 
}) ;

type

Returns the type of the value stored in the key. The return result is a string, one of string set list zset hash none, where none means the key does not exist.

$redis->type('key', function ($result) {
    var_dump($result); // string set list zset hash none
}) ;

append

If the key already exists and is a string, the APPEND command appends value to the end of the original value of the key and returns the length of the string.

If the key does not exist, APPEND simply sets the given key to value, similar to executing SET key value, and returns the length of the string.

If the key exists but is not a string, it returns false.

$redis->set('key', 'value1');
$redis->append('key', 'value2', function ($result) {
    var_dump($result); // 12
}) ; 
$redis->get('key', function ($result) {
    var_dump($result); // 'value1value2'
}) ;

getRange

Get a substring of the string stored in the specified key. The range of the substring is determined by the start and end offsets (including start and end). If the key does not exist, it returns an empty string. If the key is not of string type, it returns false.

$redis->set('key', 'string value');
$redis->getRange('key', 0, 5, function ($result) {
    var_dump($result); // 'string'
}) ; 
$redis->getRange('key', -5, -1 , function ($result) {
    var_dump($result); // 'value'
}) ;

setRange

Overwrite the value stored in the given key with the specified string, starting from the offset position. If the key does not exist, the key will be set to the specified string. If the key is not of string type, it returns false.

The return result is the length of the modified string.

$redis->set('key', 'Hello world');
$redis->setRange('key', 6, "redis", function ($result) {
    var_dump($result); // 11
}) ; 
$redis->get('key', function ($result) {
    var_dump($result); // 'Hello redis'
}) ; 

strLen

Get the length of the string value stored in the specified key. Returns false when the key does not store a string value.

$redis->set('key', 'value');
$redis->strlen('key', function ($result) {
    var_dump($result); // 5
}) ; 

getBit

For the string value stored in the key, get the bit at the specified offset.

$redis->set('key', "\x7f"); // this is 0111 1111
$redis->getBit('key', 0, function ($result) {
    var_dump($result); // 0
}) ; 

setBit

For the string value stored in the key, set or clear the bit at the specified offset.
The return value is 0 or 1, which is the value before modification.

$redis->set('key', "*");    // ord("*") = 42 = 0x2f = "0010 1010"
$redis->setBit('key', 5, 1, function ($result) {
    var_dump($result); // 0
}) ; 

bitOp

Perform bitwise operations among multiple keys (including string values) and store the results in the target key.

BITOP commands support four bitwise operations: AND, OR, XOR, and NOT.

The return result is the size of the string stored in the target key, which is equal to the size of the longest input string.

$redis->set('key1', "abc");
$redis->bitOp( 'AND', 'dst', 'key1', 'key2', function ($result) {
    var_dump($result); // 3
}) ;

bitCount

Calculate the number of bits set in the string (population count).

By default, it checks all the bytes in the string. The count operation can only be specified in the interval passing additional parameters start and end.

Similar to the GETRANGE command, start and end can also include negative values to index bytes from the end of the string, where -1 is the last byte, -2 is the second to last character, and so on.

The result returns the number of bits with the value of 1 in the string.

Nonexistent keys are considered as empty strings, so this command will return zero.

$redis->set('key', 'hello');
$redis->bitCount( 'key', 0, 0, function ($result) {
    var_dump($result); // 3
}) ;
$redis->bitCount( 'key', function ($result) {
    var_dump($result); //21
}) ;

sort

The sort command can sort elements of lists, sets, and sorted sets.

Prototype: sort($key, $options, $callback);

Where options are the following optional keys and values

$options = [
     'by' => 'some_pattern_*',
    'limit' => [0, 1],
    'get' => 'some_other_pattern_*', // or an array of patterns
    'sort' => 'asc', // or 'desc'
    'alpha' => true,
    'store' => 'external-key'
];
$redis->del('s');
$redis->sAdd('s', 5);
$redis->sAdd('s', 4);
$redis->sAdd('s', 2);
$redis->sAdd('s', 1);
$redis->sAdd('s', 3);
$redis->sort('s', [], function ($result) {
    var_dump($result); // 1,2,3,4,5
}); 
$redis->sort('s', ['sort' => 'desc'], function ($result) {
    var_dump($result); // 5,4,3,2,1
}); 
$redis->sort('s', ['sort' => 'desc', 'store' => 'out'], function ($result) {
    var_dump($result); // (int)5
}); 

ttl, pttl

Returns the remaining expiration time of the key in seconds/milliseconds.

If the key has no ttl, it returns -1. If the key does not exist, it returns -2.

$redis->set('key', 'value', 10);
// In seconds
$redis->ttl('key', function ($result) {
    var_dump($result); // 10
});
// In milliseconds
$redis->pttl('key', function ($result) {
    var_dump($result); // 9999
});
// The key does not exist
$redis->pttl('key-not-exists', function ($result) {
    var_dump($result); // -2
});

persist

Removes the expiration time of the given key so that the key never expires.

If the removal is successful, it returns 1. If the key does not exist or has no expiration time, it returns 0. On error, it returns false.

$redis->persist('key');

mSet, mSetNx

Set multiple key-value pairs in one atomic command. mSetNx returns 1 only if all keys were set.

Returns 1 on success, 0 on failure, and false on error.

$redis->mSet(['key0' => 'value0', 'key1' => 'value1']);

hSet

Assign a value to a field in a hash table.

If the field is a new field in the hash table and the value is set successfully, it returns 1. If the field already exists in the hash table and the old value is overridden by the new value, it returns 0.

$redis->del('h');
$redis->hSet('h', 'key1', 'hello', function ($r) {
    var_dump($r); // 1
}); 
$redis->hGet('h', 'key1', function ($r) {
    var_dump($r); // hello
}); 
$redis->hSet('h', 'key1', 'plop', function ($r) {
    var_dump($r); // 0
});
$redis->hGet('h', 'key1', function ($r) {
    var_dump($r); // plop
}); 

hSetNx

Assign a value to a field that does not exist in a hash table.

If the hash table does not exist, a new hash table is created, and HSET operation is performed.

If the field already exists in the hash table, the operation is invalid.

If the key does not exist, a new hash table is created, and HSETNX command is executed.

$redis->del('h');
$redis->hSetNx('h', 'key1', 'hello', function ($r) {
    var_dump($r); // 1
});
$redis->hSetNx('h', 'key1', 'world', function ($r) {
    var_dump($r); // 0
});

hGet

Returns the value of the specified field in the hash table.

If the specified field or key does not exist, it returns null.

$redis->hGet('h', 'key1', function ($result) {
    var_dump($result);
});

hLen

Used to get the number of fields in the hash table.

When the key does not exist, it returns 0.

$redis->del('h');
$redis->hSet('h', 'key1', 'hello');
$redis->hSet('h', 'key2', 'plop');
$redis->hLen('h', function ($result) {
    var_dump($result); // 2
});

hDel

The command is used to delete one or more specified fields in the hash table key, ignoring non-existing fields.

Returns the number of successfully deleted fields, excluding ignored fields. Returns false if the key is not a hash.

$redis->hDel('h', 'key1');

hKeys

Get all fields in the hash table as an array.

If the key does not exist, it returns an empty array. If the key is not a hash, it returns false.

$redis->hKeys('key', function ($result) {
    var_dump($result);
});

hVals

Return all field values in the hash table as an array.

If the key does not exist, it returns an empty array. If the key is not a hash, it returns false.

$redis->hVals('key', function ($result) {
    var_dump($result);
});

hGetAll

Return all fields and values in the hash table as an associative array.

If the key does not exist, it returns an empty array. If the key is of non-hash type, it returns false.

$redis->del('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
$redis->hGetAll('h', function ($result) {
    var_export($result); 
});

Return

array (
    'a' => 'x',
    'b' => 'y',
    'c' => 'z',
    'd' => 't',
)

hExists

Check whether the specified field of the hash table exists. Returns 1 if it exists, 0 if the field does not exist or the key does not exist, and false on error.

$redis->hExists('h', 'a', function ($result) {
    var_dump($result); //
});

hIncrBy

Used to increment the field value in the hash table by the specified increment value.

The increment can also be negative, equivalent to performing subtraction on the specified field.

If the key of the hash table does not exist, a new hash table is created, and the HINCRBY command is executed.

If the specified field does not exist, its value is initialized to 0 before executing the command.

Executing HINCRBY on a field storing a string value will return false.

The value of this operation is constrained within 64-bit signed numerical representations.

$redis->del('h');
$redis->hIncrBy('h', 'x', 2,  function ($result) {
    var_dump($result);
});

hIncrByFloat

Similar to hIncrBy, except the increment is of floating-point type.

hMSet

Set multiple field-value pairs into a hash table simultaneously.

This command will override existing fields in the hash table.

If the hash table does not exist, an empty hash table is created, and HMSET operation is performed.

$redis->del('h');
$redis->hMSet('h', ['name' => 'Joe', 'sex' => 1])

hMGet

Return the values of one or more specified fields in the hash table as an associative array.

If the specified fields do not exist in the hash table, the corresponding field will be null. Returns false if the key is not a hash.

$redis->del('h');
$redis->hSet('h', 'field1', 'value1');
$redis->hSet('h', 'field2', 'value2');
$redis->hMGet('h', ['field1', 'field2', 'field3'], function ($r) {
    var_export($r);
});

Output

array (
 'field1' => 'value1',
 'field2' => 'value2',
 'field3' => null
)

blPop, brPop

Remove and get the first/last element of a list. If the list has no elements, the list will be blocked until it times out or an element is available to pop.

$redis = new Client('redis://127.0.0.1:6379');
$redis2 = new Client('redis://127.0.0.1:6379');

$redis->blPop(['key1', 'key2'], 10, function ($r) {
    var_export($r); // array ( 0 => 'key1', 1 => 'a')
});

Timer::add(1, function () use ($redis2) {
    $redis2->lpush('key1', 'a');
});

bRPopLPush

Remove the last element from the list and insert it at the beginning of another list; if the list has no elements, it will block the list until it times out or an element becomes available to pop. It returns null if it times out.

$redis = new Client('redis://127.0.0.1:6379');
$redis2 = new Client('redis://127.0.0.1:6379');
$redis->del(['key1', 'key2']);
$redis->bRPopLPush('key1', 'key2', 2, function ($r) {
    var_export($r);
});
Timer::add(2, function () use ($redis2) {
    $redis2->lpush('key1', 'a');
    $redis2->lRange('key2', 0, -1, function ($r) {
        var_dump($r);
    });
}, null, false);

lIndex

Get an element from the list by index. You can also use negative indices, where -1 represents the last element of the list, -2 represents the second to last element, and so on.

If the specified index is out of range in the list, it returns null. If the corresponding key is not of list type, it returns false.

$redis->del('key1');
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->lindex('key1', 0, function ($r) {
    var_dump($r); // A
});

lInsert

Insert an element before or after another element in the list. If the specified element does not exist in the list, no operation is performed.

When the list does not exist, it is treated as an empty list, and no operation is performed.

If the key is not of list type, it returns false.

$redis->del('key1');
$redis->lInsert('key1', 'after', 'A', 'X', function ($r) {
    var_dump($r); // 0
});
$redis->lPush('key1', 'A');
$redis->lPush('key1', 'B');
$redis->lPush('key1', 'C');
$redis->lInsert('key1', 'before', 'C', 'X', function ($r) {
    var_dump($r); // 4
});
$redis->lRange('key1', 0, -1, function ($r) {
    var_dump($r); // ['A', 'B', 'X', 'C']
});

lPop

Remove and return the first element of the list.

Returns null when the list key does not exist.

$redis->del('key1');
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->lPop('key1', function ($r) {
    var_dump($r); // A
});

lPush

Insert one or more values at the head of the list. If the key does not exist, an empty list will be created and an LPUSH operation will be performed. When the key exists but is not of list type, it returns false.

Note: The LPUSH command prior to Redis version 2.4 only accepts a single value.

$redis->del('key1');
$redis->lPush('key1', 'A');
$redis->lPush('key1', ['B','C']);
$redis->lRange('key1', 0, -1, function ($r) {
    var_dump($r); // ['C', 'B', 'A']
});

lPushx

Insert a value at the head of an existing list; if the list does not exist, the operation is invalid, returning 0. If the key is not of list type, it returns false.

The return value is the length of the list after the lPushx command is executed.

$redis->del('key1');
$redis->lPush('key1', 'A');
$redis->lPushx('key1', ['B','C'], function ($r) {
    var_dump($r); // 3
});
$redis->lRange('key1', 0, -1, function ($r) {
    var_dump($r); // ['C', 'B', 'A']
});

lRange

Return elements within the specified range of the list, where the range is defined by the START and END offset. Here, 0 represents the first element of the list, 1 represents the second element, and so on. You can also use negative indices, where -1 represents the last element of the list, -2 represents the second to last element, and so on.

Returns an array containing the elements within the specified range. If the key is not of list type, it returns false.

$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C');
$redis->lRange('key1', 0, -1, function ($r) {
    var_dump($r); // ['C', 'B', 'A']
});

lRem

Remove elements in the list that are equal to the parameter VALUE based on the value of parameter COUNT.

The value of COUNT can be one of the following:

  • count > 0 : Start searching from the head toward the tail, removing COUNT elements equal to VALUE.
  • count < 0 : Start searching from the tail toward the head, removing the absolute value of COUNT elements equal to VALUE.
  • count = 0 : Remove all elements equal to VALUE in the list.

Returns the number of removed elements. Returns 0 if the list does not exist. Returns false if it is not a list.

$redis->lRem('key1', 2, 'A', function ($r) {
    var_dump($r); 
});

lSet

Set the value of the element at the specified index.

Returns true on success; returns false when the index parameter exceeds the range or when performing LSET on an empty list.

$redis->lSet('key1', 0, 'X');

lTrim

Trim a list to only keep the elements within the specified range, deleting any elements outside of that range.

Index 0 represents the first element of the list, and index 1 represents the second, and so on. You can also use negative indices, where -1 represents the last element of the list, -2 represents the second to last element, and so on.

Returns true on success; returns false on failure.

$redis->del('key1');

$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C');
$redis->lRange('key1', 0, -1, function ($r) {
    var_dump($r); // ['A', 'B', 'C']
});
$redis->lTrim('key1', 0, 1);
$redis->lRange('key1', 0, -1, function ($r) {
    var_dump($r); // ['A', 'B']
});

rPop

Used to remove the last element of the list, returning the removed element.

Returns null when the list does not exist.

$redis->rPop('key1', function ($r) {
    var_dump($r);
});

rPopLPush

Remove the last element from the list and add that element to the other list, returning it.

$redis->del('x', 'y');
$redis->lPush('x', 'abc');
$redis->lPush('x', 'def');
$redis->lPush('y', '123');
$redis->lPush('y', '456');
$redis->rPopLPush('x', 'y', function ($r) {
    var_dump($r); // abc
});
$redis->lRange('x', 0, -1, function ($r) {
    var_dump($r); // ['def']
});
$redis->lRange('y', 0, -1, function ($r) {
    var_dump($r); // ['abc', '456', '123']
});

rPush

Insert one or more values at the tail (rightmost end) of the list and return the length of the list after the insertion.

If the list does not exist, an empty list will be created, and the RPUSH operation will be performed. When the list exists but is not of list type, it returns false.

Note: The RPUSH command prior to Redis version 2.4 only accepts a single value.

$redis->del('key1');
$redis->rPush('key1', 'A', function ($r) {
    var_dump($r); // 1
});

rPushX

Insert a value at the end (rightmost end) of an existing list and return the length of the list. If the list does not exist, the operation is invalid and returns 0. When the list exists but is not of list type, it returns false.

$redis->del('key1');
$redis->rPushX('key1', 'A', function ($r) {
    var_dump($r); // 0
});

lLen

Returns the length of the list. If the list key does not exist, the key is interpreted as an empty list and returns 0. If the key is not of list type, it returns false.

$redis->del('key1');
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C');
$redis->lLen('key1', function ($r) {
    var_dump($r); // 3
});

sAdd

Add one or more member elements to the set. Members that already exist in the set are ignored.

If the set key does not exist, a new set containing only the added elements is created.

When the set key is not of set type, it returns false.

Note: The SADD command prior to Redis version 2.4 only accepts a single member value.

$redis->del('key1');
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , ['member2', 'member3'], function ($r) {
    var_dump($r); // 2
});
$redis->sAdd('key1' , 'member2', function ($r) {
    var_dump($r); // 0
});

sCard

Returns the number of elements in the set. Returns 0 when the set key does not exist.

$redis->del('key1');
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3');
$redis->sCard('key1', function ($r) {
    var_dump($r); // 3
});
$redis->sCard('keyX', function ($r) {
    var_dump($r); // 0
});

sDiff

Returns the difference between the first set and the other sets, which can be considered as the unique elements of the first set. Non-existing set keys are treated as empty sets.

$redis->del('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');
$redis->sDiff(['s0', 's1', 's2'], function ($r) {
    var_dump($r); // ['2', '4']
});

sDiffStore

Store the difference between specified sets in the specified set. If the specified set key already exists, it will be overwritten.

$redis->del('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');
$redis->sDiffStore('dst', ['s0', 's1', 's2'], function ($r) {
    var_dump($r); // 2
});
$redis->sMembers('dst', function ($r) {
    var_dump($r); // ['2', '4']
});

sInter

Returns the intersection of all specified sets. Non-existing set keys are treated as empty sets. When one of the specified sets is empty, the result is also an empty set.

$redis->del('s0', 's1', 's2');
$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');
$redis->sInter(['key1', 'key2', 'key3'], function ($r) {
    var_dump($r); // ['val4', 'val3']
});

sInterStore

Store the intersection between specified sets in the specified set and return the number of elements in the set storing the intersection. If the specified set already exists, it will be overwritten.

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

$redis->sInterStore('output', 'key1', 'key2', 'key3', function ($r) {
    var_dump($r); // 2
});
$redis->sMembers('output', function ($r) {
    var_dump($r); // ['val4', 'val3']
});

sIsMember

Check whether the member element is a member of the set.

Returns 1 if the member element is a member of the set. Returns 0 if the member element is not a member of the set, or if the key does not exist. Returns false if the key is not of set type.

$redis->sIsMember('key1', 'member1', function ($r) {
    var_dump($r); 
});

sMembers

Return all members in the set. Non-existing set keys are treated as empty sets.

$redis->sMembers('s', function ($r) {
    var_dump($r); 
});

sMove

Move the specified member element from the source set to the destination set.

SMOVE is an atomic operation.

If the source set does not exist or does not contain the specified member element, the SMOVE command performs no operation and returns 0. Otherwise, the member element is removed from the source set and added to the destination set.

If the destination set already contains the member element, the SMOVE command simply removes the member element from the source set.

When the source or destination is not of set type, it returns false.

$redis->sMove('key1', 'key2', 'member13');

sPop

Remove and return a random element from the specified key's set.

Returns null when the set does not exist or is empty.

$redis->del('key1');
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3');
$redis->sPop('key1', function ($r) {
    var_dump($r); // member3
});
$redis->sAdd('key2', ['member1', 'member2', 'member3']);
$redis->sPop('key2', 3, function ($r) {
    var_dump($r); // ['member1', 'member2', 'member3']
});

sRandMember

The Redis Srandmember command is used to return a random element from the set.

Starting from Redis version 2.6, the Srandmember command accepts an optional count parameter:

  • If count is a positive number and less than the cardinality of the set, the command returns an array containing count elements, all of which are distinct. If count is greater than or equal to the cardinality of the set, the whole set is returned.
  • If count is a negative number, the command returns an array that may contain duplicate elements, with the length equal to the absolute value of count.

This operation is similar to SPOP, but while SPOP removes a random element from the set and returns it, Srandmember only returns random elements without changing the set.

$redis->del('key1');
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); 

$redis->sRandMember('key1', function ($r) {
    var_dump($r); // member1
});

$redis->sRandMember('key1', 2, function ($r) {
    var_dump($r); // ['member1', 'member2']
});
$redis->sRandMember('key1', -100, function ($r) {
    var_dump($r); // ['member1', 'member2', 'member3', 'member3', ...]
});
$redis->sRandMember('empty-set', 100, function ($r) {
    var_dump($r); // []
}); 
$redis->sRandMember('not-a-set', 100, function ($r) {
    var_dump($r); // []
});

sRem

Remove one or more member elements from the set; non-existing member elements are ignored.

Returns the number of elements successfully removed, excluding ignored elements.

When the key is not of set type, it returns false.

In Redis version 2.4, SREM only accepts a single member value.

$redis->sRem('key1', ['member2', 'member3'], function ($r) {
    var_dump($r); 
});

sUnion

The command returns the union of the specified sets. Non-existing set keys are treated as empty sets.

$redis->sUnion(['s0', 's1', 's2'], function ($r) {
    var_dump($r); // []
});

sUnionStore

Store the union of specified sets in the specified destination set and return the number of elements. If the destination already exists, it will be overwritten.

$redis->del('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');
$redis->sUnionStore('dst', 's0', 's1', 's2', function ($r) {
    var_dump($r); // 4
});
$redis->sMembers('dst', function ($r) {
    var_dump($r); // ['1', '2', '3', '4']
});