Predis is the PHP connection Redis Operation Library, because it completely uses PHP writing, a lot of use of namespaces and closures and other functions, only support php5.3 above, so the measured performance, 25,000 times per second read and write.
It's also easy to store session data in Redis:
Session.save_handler = Redis
Session.save_path = "Tcp://127.0.0.1:6379″
The following is a summary of some operations.
Use AutoLoad to load the relevant library, the focus here is to require $file; Spl_autoload_register (function ($class) {$file = __dir__. ' /lib/predis/'. $class.
PHP ';
if (file_exists ($file)) {require $file;
return true;
}
}); Configure the connected IP, port, and corresponding database $server = Array (' host ' = ' 127.0.0.1 ', ' port ' = 6379, ' db ' = 1
5);
$redis = new Client ($server);
Normal set/get operation $redis->set (' library ', ' Predis ');
$retval = $redis->get (' library '); Echo $retval; Display ' Predis '//setex set a storage aging $redis->setex (' str ', ' Ten, ' Bar '); Indicates that the storage is valid for 10 seconds//setnx/msetnx equivalent to the add operation, does not overwrite the existing value $redis->setnx (' foo ', 12); True $redis->setnx (' foo ', 34); False//getset operation, set variant, results return the value before the replacement $redis->getset (' foo ', 56);//returns the increment and decrement of the value of the INCRBY/INCR/DECRBY/DECR//, $redis-& GT;INCR (' foo '); Foo is $redis->incrby (' foo ', 2); Foo//exists detects if there is a value $redis->exists (' foo '),//true//del Delete $redis->del (' foo ');//true//type type detection, string return str ING, LIST returns list,set table returns Set/zset,hash table returns hash $redis->type (' foo ');//does not exist, returns none $redis->set (' str ', ' test '); $redis->type (' str '); String that returns string//append to the existing string $redis->append (' str ', ' _123 '); Returns the cumulative string length of 8, this input str for the ' test_123 '//setrange partial replacement Operation $redis->setrange (' str ', 0, ' abc '); Returns 3, the parameter 2 is 0 o'clock equivalent to the set Operation $redis->setrange (' str ', 2, ' CD '), or//returns 4, indicating the substitution from the 2nd word specifier, at which point ' str ' for the ' ABCD '//substr section gets the operation $redis- >substr (' str ', 0,2);//Represents the 2nd character from the No. 0, a total of 3, returns the ' ABC '//strlen gets the string length $redis->strlen (' str '); Returns 4//setbit/getbit bits stored and obtained $redis->setbit (' binary ', 31, 1); 1 in the 31st place, there may be a size end problem? But it doesn't matter, getbit should not have problems $redis->getbit (' binary ', 31);
Returns the 1//keys Fuzzy Lookup function, which supports the * number as well as the number (matches one character) $redis->set (' foo1 ', 123);
$redis->set (' Foo2 ', 456); $redis->keys (' foo* '); Returns an array of foo1 and Foo2 $redis->keys (' F?o? '); Ibid.//randomkey randomly returns a key $redis->randomkey (); It is possible to return ' foo1 ' or ' foo2 ' and any other Redis key//rename/renamenx to rename the key, the difference is that the Renamenx is not allowed to change to the existing key $redis->rename (' Str ', ' str2 '); Changed the key named ' str ' to ' str2 '//expire setting Key-value's timeliness, TTL gets the remaining validity period, persist reset to permanent storage $redis->expire (' foo ', 1); Set valid for 1 seconds $redis->ttl (' foo '); Returns the validity value of 1s $redis->expire (' foo ');
Cancels the expire behavior//dbsize returns the total number of records in the current database for Redis $redis->dbsize (); /* Queue operation *///RPUSH/RPUSHX ordered list operations, inserting elements from the queue//lpush/lpushx and rpush/rpushx are inserted into the head of the queue, as above, ' X ' means to operate only on existing keys $redis Rpush (' foolist ', ' bar1 '); Returns the length of a list of 1 $redis->lpush (' foolist ', ' bar0 '); Returns the length of a list of 2 $redis->rpushx (' foolist ', ' bar2 '); Returns 3,RPUSHX only adds to an existing queue, otherwise returns 0//llen returns the current list length $redis->llen (' foolist ');//3//lrange Returns an element of an interval in the queue $redis->lrange (' Foolist ', 0, 1); The returned array contains the NO. 0 to 1th total of 2 elements $redis->lrange (' foolist ', 0,-1);//returns NO. 0 to the penultimate, which is equivalent to returning all elements, noting that many times Redis uses negative numbers, and//lindex Returns the list element $redis->lindex (' foolist ', 1) in the specified order position; Return ' bar1 '//lset Modify the value of the specified position in the queue $redis->lset (' foolist ', 1, ' 123 ');//Modify the element of position 1, return true//lrem delete the specified number of characters from the left in the queue $redis- >lrem (' Foolist ', 1, ' _ '); Delete Queue left (use-1) 1 characters ' _ ' (if any)//lpop/rpop a stack-like structure to eject (and delete) the leftmost or most right element $redis->lpop (' foolist '); ' Bar0 ' $redis->rpoP (' foolist '); The ' bar2 '//ltrim queue is modified, leaving several elements on the left, remaining deleted $redis->ltrim (' foolist ', 0,1);
Keep No. 0 to 1th elements from the left//rpoplpush the pop element from one queue and push it to another queue $redis->rpush (' List1 ', ' ab0 ');
$redis->rpush (' List1 ', ' ab1 ');
$redis->rpush (' List2 ', ' ab2 ');
$redis->rpush (' List2 ', ' ab3 '); $redis->rpoplpush (' List1 ', ' list2 ');//Results List1 =>array (' ab0 '), List2 =>array (' ab1 ', ' ab2 ', ' ab3 ') $redis
Rpoplpush (' List2 ', ' list2 ');//apply to the same queue, move the last element to the head list2 =>array (' ab3 ', ' ab1 ', ' ab2 ')//linsert insert elements before or after the specified element in the middle of the queue $redis->linsert (' List2 ', ' before ', ' ab1 ', ' 123 '); Represents the insertion of ' 123 ' before the element ' AB1 ' $redis->linsert (' List2 ', ' after ', ' ab1 ', ' 456 '); Indicates that the insertion of ' 456 ' after the element ' AB1 '//blpop/brpop blocks and waits for a queue to be empty, then pops out of the leftmost or most right element (this function can be said to be very useful outside of PHP)//brpoplpush is also blocking and waiting for the operation, Results same as Rpoplpush $redis->blpop (' List3 ', 10);
If List3 is empty, wait until the first element pops up when not empty, after 10 seconds Timeout/** Set table operation *///sadd add element, return True, repeat return false $redis->sadd (' Set1 ', ' ab ');
$redis->sadd (' Set1 ', ' CD ');
$redis->sadd (' Set1 ', ' ef '); Srem removes the specified element $redis->srem (' Set1 ', ' Cd ');
Remove the ' CD ' element//spop pop-up element $redis->spop (' Set1 ');
Smove moves the specified element of the current set table to another set table $redis->sadd (' Set2 ', ' 123 '); $redis->smove (' Set1 ', ' Set2 ', ' ab ');//move ' ab ' to ' set2 ' in ' Set1 ', return True or False//scard return the current set TABLE element count $redis->scard ( ' Set2 ');//2//sismember determines whether the element belongs to the current table $redis->sismember (' Set2 ', ' 123 '); True or False//smembers returns all elements of the current table $redis->smembers (' Set2 ');
Array (' 123 ', ' AB ');
Sinter/sunion/sdiff returns the intersection/set/complement of elements in two tables $redis->sadd (' Set1 ', ' ab '); $redis->sinter (' Set2 ', ' Set1 ');
Returns an array (' AB ')//sinterstore/sunionstore/sdiffstore the two table intersection/set/complement elements to the third table $redis->set (' foo ', 0); $redis->sinterstore (' foo ', ' Set1 '); This is equivalent to copy ' Set1 ' content to ' foo ' and ' foo ' to set table $redis->sinterstore (' foo ', Array (' Set1 ', ' Set2 '));
Copy the same elements in ' Set1 ' and ' Set2 ' to the ' Foo ' table, overwriting the original contents of ' foo '//srandmember return a random element in the table $redis->srandmember (' Set1 ');
/** ordered Set table operation *///sadd add element and set ordinal, return True, repeat return false $redis->zadd (' Zset1 ', 1, ' AB ');
$redis->zadd (' Zset1 ', 2, ' CD '); $redis->zadd (' Zset1 ', 3, ' EF '); Zincrby changes the index value of the specified element, changing the order of the Elements $redis->zincrby (' Zset1 ', ten, ' ab ');//returns one//ZREM removes the specified element $redis->zrem (' Zset1 ', ' EF '); True or False//zrange returns the elements of the specified interval in the table in the order of position $redis->zrange (' Zset1 ', 0, 1);
Returns the element between position 0 and 1 (two) $redis->zrange (' Zset1 ', 0,-1);//returns the element (equivalent to all elements) between position 0 and the first element of the countdown,//zrevrange, returns the elements of the specified interval in the table, inverted sequentially $redis->zrevrange (' Zset1 ', 0,-1);
Element order and Zrange reverse//zrangebyscore/zrevrangebyscore returns the elements of the specified index interval in order/descending form $redis->zadd (' Zset1 ', 3, ' EF ');
$redis->zadd (' Zset1 ', 5, ' GH '); $redis->zrangebyscore (' Zset1 ', 2,9); Returns the index value 2-9 between the elements of array (' EF ', ' gh ')//Parameter form $redis->zrangebyscore (' Zset1 ', 2,9, ' withscores '); Returns an element between the index value 2-9 and contains an index value of array (' EF ', 3), array (' GH ', 5)) $redis->zrangebyscore (' Zset1 ', 2,9,array (' Withscores ') =>true, ' Limit ' =>array (1, 2)); Returns the element between the index value 2-9, ' Withscores ' =>true that contains the index value; ' Limit ' =>array (1, 2), which indicates a maximum of 2 returns, the result is an array (' EF ', 3), array (' GH ', 5))//zunionstore/zinterstore the set of multiple tables/ The intersection is deposited in another table $redis->zunionstore (' Zset3 ', Array (' Zset1 ', ' Zset2 ', ' zset0 ')); Put ' Zset1 ', ' Zset2 ', ' zset0 ' in the same set of ' zset3 '//Other parameters $redis->zunionstore (' Zset3 ', Array (' Zset1 ', ' Zset2 '), Array (' Weights ' = = Array (5,0))); The//weights parameter represents a weight, in which an element with a value greater than 5 after the sum of the set is in front of the row, greater than 0 $redis->zunionstore (' Zset3 ', Array (' Zset1 ', ' Zset2 '), Array (' aggregate ' = ' max ')),//' aggregate ' + ' max ' or ' min ' indicates that the same element after the set is either a large value or a small value//zcount Count the number of elements in an index interval $redis->zcount (' Zset1 ', 3,5),//2 $redis->zcount (' Zset1 ', ' (3 ', 5)); ' (3 ' means that the index value is between 3-5 but not 3, it is also possible to use ' (5 ') for a maximum of 5 but not 5//zcard statistical elements $redis->zcard (' Zset1 ');//4//zscore the index of the query element $redis- >zscore (' Zset1 ', ' ef ');//3//zremrangebyscore Delete an element of an index interval $redis->zremrangebyscore (' Zset1 ', 0,2); Remove the index between 0-2 elements (' AB ', ' CD '), return the number of deleted elements 2//zrank/zrevrank return the element in the table order/descending position (not the index) $redis->zrank (' Zset1 ', ' ef ');//Return 0, Because it is the first element, Zrevrank returns 1 (the last)//zremrangebyrank deletes the element in the specified position interval in the table $redis->zremrangebyrank (' Zset1 ', 0,10); Delete element with position 0-10, return deleted element number 2/** Hash table operation *///hset/hget access hash table data $redis->hset (' hash1 ', ' key1 ', ' v1 '); Save key ' Key1 ' value as ' v1 ' element into the HASH1 table $rediS->hset (' Hash1 ', ' key2 ', ' v2 '); $redis->hget (' hash1 ', ' key1 '); Take out the value of key ' key1 ' in table ' Hash1 ', return ' v1 '//hexists returns the existence of the specified key in the hash table $redis->hexists (' hash1 ', ' key1 '); True or False//hdel removes the element of the specified key in the hash table $redis->hdel (' hash1 ', ' key2 '); True or False//hlen returns the number of hash table elements $redis->hlen (' hash1 '); 1//hsetnx adds an element, but cannot repeat $redis->hsetnx (' hash1 ', ' key1 ', ' v2 '); False $redis->hsetnx (' hash1 ', ' key2 ', ' v2 ');
True//hmset/hmget accesses multiple elements to the hash table $redis->hmset (' Hash1 ', Array (' key3 ' = ' v3 ', ' key4 ' = ' v4 ')); $redis->hmget (' Hash1 ', Array (' Key3 ', ' Key4 ')); Returns the corresponding value of array (' V3 ', ' v4 ')//hincrby the specified key to accumulate $redis->hincrby (' hash1 ', ' Key5 ', 3); Returns 3 $redis->hincrby (' hash1 ', ' Key5 ', 10); Returns the//hkeys of all keys $redis->hkeys (' Hash1 ') in the hash table; Returns the array (' Key1 ', ' key2 ', ' Key3 ', ' key4 ', ' key5 ')//hvals returns all value $redis->hvals (' Hash1 ') in the hash table; Returns an array (' V1 ', ' v2 ', ' v3 ', ' v4 ', '//hgetall ') to return the entire hash table element $redis->hgetall (' hash1 '); Return Array (' key1 ' = ' v1 ', ' key2 ' = ' v2 ', ' key3 ' => ' v3 ', ' key4 ' = ' v4 ', ' key5 ' =>13 '/** sort operation *///sort sort $redis->rpush (' tab ', 3);
$redis->rpush (' tab ', 2);
$redis->rpush (' tab ', 17); $redis->sort (' tab '); Returns an array (2,3,17)//using parameters that can be combined using the array (' sort ' = = ' desc ', ' limit ' = = = Array (1, 2)) $redis->sort (' tab ', Array (' sort ') = ' desc ')); In descending order, returns an array (17,3,2) $redis->sort (' tab ', Array (' limit ' = = ' Array (1, 2))); Returns the 1 element in the order position 2 (where 2 is the number, not the position), returns an array (3,17) $redis->sort (' tab ', Array (' limit ' = = Array (' alpha ' = ') ')) ; Sort by first character to return array (17,2,3), because the first character of 17 is ' 1 ' so the first line is placed $redis->sort (' tab ', Array (' limit ' = = ' = ' ordered ') )); Represents a permanent sort, returning the number of elements $redis->sort (' tab ', Array (' limit ' = = ' Array (' get ' = ' pre_* ')); The wildcard ' * ' filter element is used to return only elements that begin with ' pre_ '/** redis Management operations *///SELECT specifies the database to be manipulated $redis->select (' mydb ');
Specified as MyDB, does not exist create//flushdb to empty the current library $redis->flushdb ();
Move moves the elements of the library into other libraries $redis->set (' foo ', ' Bar '); $redis->move (' foo ', ' mydb2 '); If ' MYDB2 ' inventory is displayed in the//info service as status information $redis-> info (); slaveof configuration from server $redis->slaveof (' 127.0.0.1 ', 80); Configure the 127.0.0.1 port 80 server to $redis->slaveof () from the server;
Clear from server//Synchronize Save server data to disk $redis->save ();
Asynchronously saves server data to disk $redis->bgsave ();
//??
$redis->bgrewriteaof ();
Returns the last time the disk was updated $redis->lastsave (); Set/get multiple Key-value $mkv = Array (' usr:0001 ' = ' first user ', ' usr:0002 ' = ' Second user ', ' usr:0003 ' =
> ' third user '); $redis->mset ($mkv); Store multiple keys corresponding to the value $retval = $redis->mget (Array_keys ($mkv));
Gets the value Print_r ($retval) corresponding to multiple keys;
Bulk Operation $replies = $redis->pipeline (function ($pipe) {$pipe->ping ();
$pipe->flushdb (); $pipe->incrby (' counter ', 10);
Incremental Operation $pipe->incrby (' counter ', 30);
$pipe->exists (' counter ');
$pipe->get (' counter ');
$pipe->mget (' does_not_exist ', ' counter ');
});
Print_r ($replies);
CAS, transactional operation function Zpop ($client, $zsetKey) {$element = null; $options = Array (' cas ' = = true,//Initialize with SuppORT for CAS Operations ' watch ' + $zsetKey,//Key that needs-be-watched to detect changes ' retry ' = > 3,//number of retries on aborted transactions, after//which the client bails
An exception.
); $txReply = $client->multiexec ($options, function ($TX) use ($zsetKey, & $element) {@list ($element) =
$tx->zrange ($zsetKey, 0, 0); if (Isset ($element)) {$tx->multi ();
With CAS, MULTI *must* is explicitly invoked.
$tx->zrem ($zsetKey, $element);
}
});
return $element;
} $zpopped = Zpop ($redis, ' zset '); echo isset ($zpopped)?
"Zpoped $zpopped": "Nothing to zpop!", "\ n";
Prefix the access key, such as: ' NRK: ' $redis->getprofile ()->setpreprocessor (New Keyprefixpreprocessor (' NRK: '));
Some methods of distributed storage $multiple _servers = Array (' host ' = ' 127.0.0.1 ', ' port ' = 6379, ' Database ' = ' alIAS ' = ' first ', ', ' Array (' host ' = ' 127.0.0.1 ', ' port ' = 6380, ' Databa
Se ' = +, ' Alias ' = ' second ',);
Use Predis\distribution\idistributionstrategy;
Class Naivedistributionstrategy implements Idistributionstrategy {private $_nodes, $_nodescount;
Public Function __constructor () {$this->_nodes = array ();
$this->_nodescount = 0;
Public function Add ($node, $weight = null) {$this->_nodes[] = $node;
$this->_nodescount++; The Public function remove ($node) {$this->_nodes = Array_filter ($this->_nodes, function ($n) use ($node)
{return $n!== $node;
});
$this->_nodescount = count ($this->_nodes);
Public function Get ($key) {$count = $this->_nodescount;
if ($count = = = 0) {throw new RuntimeException (' No connections '); } return $this-> _nodes[$count > 1 abs (CRC32 ($key)% $count): 0];
Public Function GenerateKey ($value) {return CRC32 ($value);
}}//configuration key Distribution Policy $options = Array (' key_distribution ' = = new Naivedistributionstrategy (),);
$redis = new Predis\client ($multiple _servers, $options);
for ($i = 0; $i set ("Key: $i", Str_pad ($i, 4, ' 0 ', 0));
$redis->get ("Key: $i");
} $server 1 = $redis->getclientfor (' first ')->info ();
$server 2 = $redis->getclientfor (' second ')->info (); printf ("Server '%s ' has%d keys while server '%s ' has%d keys.\n", ' first ', $server 1[' db15 ' [' Keys '], ' second ', $serve r2[' DB15 ' [' Keys ']);