phpRedis操作整理

7 篇文章 0 订阅

PhpRedis:

Github:https://github.com/phpredis/phpredis
中文文档:http://redisdoc.com/
其他资料:http://redisinaction.com/preview/appendx-b.html


PHP Session handler


php redis 扩展可以存储session 修改php.ini
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"

参数:
weight 比重
timeout 超时
persistent 持久连接 取值 0 1
prefix session id 前缀
auth 验证
database 选择的数据库

session 以秒表示 生命周期由session.gc_maxlifetime来控制
ini_set('session.gc_maxlifetime','3600')可改变生存时间,需要SETEX 命令,redis版本至少2.0

phpredis 也可以链接一个unix domain socket :unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0



Classes and methods

Class Redis
$redis = new Redis();

Predefined constants
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

connect //BOOL
$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 //BOOL

$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 //BOOL
$redis->auth('authString');

select //BOOL
$redis->select(0);  // switch to DB 0

setOption //BOOL
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE);   // don't serialize data
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);    // use built-in serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);   // use igBinary serialize/unserialize
$redis->setOption(Redis::OPT_PREFIX, 'myAppName:'); // use custom prefix on all keys

getOption //value
$redis->getOption(Redis::OPT_SERIALIZER);   // return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, or Redis::SERIALIZER_IGBINARY.

ping //string "+PONG" is success, throws a RedisException object on connectivity error


Server

bgrewriteaof //BOOL

//Start the background rewrite of AOF
$redis->bgrewriteaof();


bgsave //BOOL  If a save is already running, this command will fail and return FALSE.
//Asynchronously save the dataset to disk (in background)
$redis->bgSave();
$redis->save();//Synchronously


config // value for get  bool for set
//Get or Set the Redis server configuration parameters.
$redis->config("GET", "*max-*-entries*");
$redis->config("SET", "dir", "/var/run/redis/dumps/");


dbSize //int
//Return the number of keys in selected database.
$count = $redis->dbSize();


flushAll //BOOL
//Remove all keys from all databases.
$redis->flushAll();


flushDB //BOOL always true
// Remove all keys from the current database.
$redis->flushDB();


info
//Get information and statistics about the server
$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 */
$redis->resetStat(); reset statistics


lastSave //int
//Returns the timestamp of the last disk save.返回最后一次保存到磁盘的时间戳
$redis->lastSave();


slaveof //BOOL
//Changes the slave status   Either host (string) and port (int), or no parameter to stop being a slave.
$redis->slaveof('10.0.1.7', 6379);
/* ... */
$redis->slaveof();


time //int
//Return the current server time.
$redis->time();


slowlog

// 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


$redis->get('key');//String or Bool: If key didn't exist, FALSE is returned. Otherwise, the value related to this key is returned.


set //BOOL
// Simple key -> value set
$redis->set('key', 'value');

// Will redirect, and actually make an SETEX call ,Redis >= 2.6.12
$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//BOOL second  millisecond
$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 //BOOL
$redis->setnx('key', 'value'); /* return TRUE */
$redis->setnx('key', 'value'); /* return FALSE */


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


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


incr, incrBy(decr, decrBy) //int the new value
$redis->incr('key1'); /* key1 didn't exists, set to 0 before the increment  and now has the value 1  */
$redis->incr('key1'); /* 2 */
$redis->incrBy('key1', 10); /* 12 */


incrByFloat // float
$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 */


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


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


randomKey 
//Returns a random key. an existing key in redis.
$key = $redis->randomKey();
$surprise = $redis->get($key);  // who knows what's in there.


move //BOOL
//Moves a key to a different database.
$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 //BOOL
$redis->set('x', '42');
$redis->rename('x', 'y');
$redis->get('y');   // → 42
$redis->get('x');   // → `FALSE`


renameNx //Same as rename, but will not replace a key if the destination already exists. This is the same behaviour as setNx.type


expire, setTimeout, pexpire //BOOL
$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 //BOOl
$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 // Array
$allKeys = $redis->keys('*');   // all keys will match this.
$keyWithUserPrefix = $redis->keys('user*');


scan //Array or BOOL 
//Scan the keyspace for keys
$it = NULL; /* Initialize our iterator to NULL */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); /* retry when we get no keys back */
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";
}


type
//Returns the type of data pointed by a given key.
$redis->type('key');


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


getRange // substring
//Return a substring of a larger string
$redis->set('key', 'string value');
$redis->getRange('key', 0, 5); /* 'string' */
$redis->getRange('key', -5, -1); /* 'value' */


setRange //int
//Changes a substring of a larger string.
$redis->set('key', 'Hello world');
$redis->setRange('key', 6, "redis"); /* returns 11 */
$redis->get('key'); /* "Hello redis" */


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


getBit //long
//Return a single bit out of a larger string
//key  offset(index)
$redis->set('key', "\x7f"); // this is 0111 1111
$redis->getBit('key', 0); /* 0 */
$redis->getBit('key', 1); /* 1 */


setBit // long 1 or 0
//Changes a single bit of a string.
//key  offset  value: bool or int (1 or 0)
$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 // long
//operation: either "AND", "OR", "NOT", "XOR"
//ret_key: return key
//key1  key2...
$redis->bitop('AND',key,key1,key2);


bitcount // long
//Count bits in a string.
$redis->bitcount('key');


sort // array or num
//Sort the elements in a list, set or sorted set.
//optional => 
/*
'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'
*/
$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 // long
//Returns the time to live left for a given key in seconds (ttl), or milliseconds (pttl).
$redis->ttl('key');


persist // BOOL
//Remove the expiration timer from a key.
$redis->persist('key');


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


dump //The Redis encoded value of the key, or FALSE if the key doesn't exist
$redis->set('foo', 'bar');
$val = $redis->dump('foo'); // $val will be the Redis encoded key value


restore
//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)
$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
//Migrates a key to a different Redis instance. 迁移一个key 到另一个redis实例
/*host string. The destination host
port integer. The TCP port to connect to.
key string. The key to migrate.
destination-db integer. The target DB.
timeout integer. The maximum amount of time given to this transfer.*/
$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 */



Hashes


hSet
//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.
$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 //BOOL
$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 //string or false
$redis->hGet('h', 'key1');


hLen //int or FALSE if the key doesn't exist or isn't a hash.
$redis->delete('h')
$redis->hSet('h', 'key1', 'hello');
$redis->hSet('h', 'key2', 'plop');
$redis->hLen('h'); /* returns 2 */


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


hKeys //array, like  PHP's array_keys()
var_dump($redis->hKeys('h'));


hVals // like PHP's array_values().
var_dump($redis->hVals('h'));


hGetAll //key=>value array
var_dump($redis->hGetAll('h'));


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


hIncrBy //new value
$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 //new value
$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 //bool
$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
//array
$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 //array
$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 */
    }
}



Lists


blPop, brPop
//ARRAY array('listName', 'element')
//阻塞式弹出元素
/* 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 //string or FALSE in case of timeout.
//阻塞式rpoplpush


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


lInsert // The number of the elements in the list, -1 if the pivot didn't exists.
// Insert value in the list before or after the pivot value.
$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 //string or bool
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->lPop('key1'); /* key1 => [ 'B', 'C' ] */


lPush // element number or string
$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 //new length or false
$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 //array
//key start end
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C');
$redis->lRange('key1', 0, -1); /* array('A', 'B', 'C') */


lRem, lRemove //the number of elements to remove  or  if the value identified by key is not a list ,false
//key value count
$redis->lRem('key1', 'A', 2); /* 2 */


lSet //BOOl
//key index value
$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 //array or false

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


rPop //string or false
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->rPop('key1'); /* key1 => [ 'A', 'B' ] */


rpoplpush //BOOL
//Key: srckey  Key: dstkey
var_dump($redis->rpoplpush('x', 'y'));


rPush //new length or false

$redis->rPush('key1', 'C'); // returns 3


rPushx //new length or false
$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 //length or false

$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 //LONG
 
$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 //number or 0(set doesn't exist)
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/
$redis->sCard('key1'); /* 3 */
$redis->sCard('keyX'); /* 0 */


sDiff //Array of strings: The difference of the first set will all the others.
$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'));/*array(4,2)*/


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


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


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


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


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


sIsMember, sContains //BOOL
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/
$redis->sIsMember('key1', 'member1'); /* TRUE */
$redis->sIsMember('key1', 'memberX'); /* FALSE */


sMembers, sGetMembers //array
var_dump($redis->sMembers('s'));


sMove  //BOOL

$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 //string or false if set identified by key is empty or doesn't exist. (random and remove)
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/
$redis->sPop('key1'); /* 'member1', 'key1' => {'member3', 'member2'} */
$redis->sPop('key1'); /* 'member3', 'key1' => {'member2'} */


sRandMember //(random without remove)
$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
//removed num
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/
$redis->sRem('key1', 'member2', 'member3'); /*return 2. 'key1' => {'member1'} */


sScan 
$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
// Long 1 if the element is added. 0 otherwise.
$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 //int
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zSize('key'); /* 3 */


zCount //int
//(zRangeByScore) key start: string end: string
$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 //DOUBLE the new value
// key value member
$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 //The number of values in the new sorted set.
/*
keyOutput
arrayZSetKeys
arrayWeights
aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zInter.
*/
$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') */


zUnion 
$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') */


zRange //Array 
//key start: long end: long withscores: bool = false
$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 //Array 
//key  start: string  end: string  options: array
$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 //Array 
/*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.*/
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 //long
//返回元素的排名(按score 从小到大排序)即下标,非score
$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 //1 on success, 0 on failure.
$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 //The number of values deleted from the sorted set
//key  start: LONG  end: LONG
$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
$redis->zRemRangeByScore('key', 0, 3); /* 2 */


zRevRange
//key start: long end: long withscores: bool = false
$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 //double
$redis->zAdd('key', 2.5, 'val2');
$redis->zScore('key', 'val2'); /* 2.5 */


zScan //Array or bool
$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";
    }
}




Pub/sub


publish
//Publish messages to channels. Warning: this function will probably change in the future.
$redis->publish('chan-1', 'hello, world!'); // send message.


subscribe //Subscribe to channels. Warning: this function will probably change in the future.
/*
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.*/
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 //A command allowing you to get information on the Redis pub/sub system.
$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'*/
$redsi->pubsub("numpat"); /* Get the number of pattern subscribers */




Transactions


multi, exec, discard
//transactional
//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.
$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 //Watches 
$redis->watch('x');
/* long code here during the execution of which other clients could well modify `x` */
$ret = $redis->multi()
    ->incr('x')
    ->exec();
/*
$ret = FALSE if x has been modified between the call to WATCH and the call to EXEC.
*/


getLastError
//The last error message (if any)
$err = $redis->getLastError(); 


clearLastError
//Clear the last error message
$redis->clearLastError();


_prefix //  A utility method to prefix the value with the prefix setting for phpredis.
$redis->setOption(Redis::OPT_PREFIX, 'my-prefix:');
$redis->_prefix('my-value'); // Will return 'my-prefix:my-value'


_serialize
$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
$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)


IsConnected
GetHost
GetPort
getDBNum
GetTimeout
GetReadTimeout
GetPersistentID
GetAuth

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值