Predis is a PHP connection Redis operation Library, because it completely use PHP writing, a lot of use of namespaces and closures and other functions, only support php5.3 above version, so the measured performance, 25,000 times per second read and write, I believe that the C language written by PHP extension performance will greatly improve ( For example, use C extension Phpredis Https://github.com/owlient/phpredis).
It's also easy to store session data in Redis:
Session.save_handler = Redis
Session.save_path = "Tcp://127.0.0.1:6379″
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 , ' database ' => 15); $redis = new client ($server);//General set/ Get Operation $redis->set (' Library ', ' Predis '), $retval = $redis->get (' library ');echo $retval; //display ' Predis '//setex set a storage aging $redis->setex (' str ', 10, ' bar '); //means storage is valid for 10 seconds Setnx/msetnx equivalent to the add operation, does not overwrite the existing value $redis->setnx (' foo '); //true$redis->Setnx (' foo '), //false//getset operation, set variant, results return the value before replacement $redis->getset (' foo ', 56);//Return 34// INCRBY/INCR /decrby/decr increment and decrement of Values $REDIS->INCR (' foo '), //foo to 57$redis->incrby (' foo ', 2); //foo to 59// exists detects if there is a value $redis->exists (' foo ');//true//del delete $redis->del (' foo ');//true//type type detection, The string returned by the list,set table returns the Set/zset,hash table return Hash$redis->type (' foo '), or//not present, returning None$redis->set (' str ', ' Test '); $redis->type (' str '); //string, return string//append to the existing string $redis->append (' str ', ' _123 '); //returns the cumulative string length of 8, this input str for ' test_123 '//setrange partial replacement Operation $redis->setrange (' str ', 0, ' abc '); // Return 3, Parameter 2 is 0 o'clock equivalent to the set Operation $redis->setrange (' str ', 2, ' CD ');//Return 4, representing the 2nd word specifier replace, then ' str ' for ' ABCD '//substr partial get operation $ Redis->substr (' str ', 0,2);//Represents the 2nd character from No. 0, a total of 3, return ' abc '//strlen get string length $redis->strlen (' str '); / /return 4//setbit/getbit bit to store and get $redis->setbit (' binary ', 31,1); //says 1 in 31st place, there may be a size end problem? But it doesn't matter, getbit should not have a problem $redis->getbit(' binary ', +); //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* '); //return foo1 and Foo2 (' F array$redis->keys '); //Ibid//randomkey randomly returns a Key$redis->randomkey (); //may be back ' foo1 ' or ' Foo2 ' And any other Redis key//rename/renamenx to rename the key, the difference is that Renamenx is not allowed to change to existing key$redis->rename (' str ', ' str2 '); //renamed ' str ' key to ' str2 '//expire set Key-value's timeliness,ttl get remaining validity,persist reset to permanent storage $redis- >expire (' foo ', 1), //set is valid for 1 seconds $redis->ttl (' foo '), //returns the validity value 1s$redis->expire (' foo '); //cancels expire behavior//dbsize returns the total number of records in the current database $redis->dbsize ();/* Queue operations *///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 1$redis->lpush (' foolist ', ' bar0 '); //returns the length of a list 2$redis->rpushx (' Foolist ', ' bar2 '); //returns 3,RPUSHX only adds to the 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 No. 0 to 1th of a total of 2 elements $redis->lrange (' foolist ', 0,-1);//return No. 0 to the penultimate, equivalent to return all elements, note that Redis often uses negative numbers, the same as//lindex Returns the list element $redis->lindex (' foolist ', 1) in the specified order position, //returns ' Bar1 '//lset modifies the value$redis->lset of the specified position in the queue (' Foolist ', 1, ' 123 ');//Modify the element of position 1, return true//lrem the specified number of characters from the left in the delete queue $redis->lrem (' Foolist ', 1, ' _ '); //Delete queue from left ( Right up using-1) 1 characters ' _ ' (if any)//lpop/rpop like a stack structure to pop (and delete) the leftmost or most right element $redis->lpop (' foolist '); //' Bar0 ' $redis Rpop (' foolist '); //' bar2 '//ltrim queue 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 ') ) and//apply to the same queue, putting the lastElements are moved to the head list2 =>array (' ab3 ', ' ab1 ', ' ab2 ')//linsert in the middle of the queue by specifying elements before or after inserting elements $redis->linsert (' List2 ', ' before ', ' ab1 ', ' 123 '), //means inserting ' ab1 ' before element ' 123 ' $redis->linsert (' List2 ', ' after ', ' ab1 ', ' 456 '); //means that after the element ' AB1 ' is inserted ' 456 '//blpop/brpop block and wait for a queue to not be empty, then pop out 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, the result is the same as the Rpoplpush $redis->blpop (' List3 ', ten); //if the list3 is empty, wait until the first element pops up when it is 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 ' CD ' element//spop popup first 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 returns the number of elements in the current set table $redis->scard (' Set2 ');//2//sismember determine 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 '), //return Array (' AB ')//sinterstore/sunionstore/sdiffstore Copy two table intersection/set/complement elements into the third table $redis->set (' foo ', 0), $redis->sinterstore (' foo ', ' Set1 '); //side is equivalent to ' Set1 ' Content copy to ' foo ' and ' foo ' to set table $redis->sinterstore (' foo ', Array (' Set1 ', ' Set2 ')); //will ' Set1 ' and ' Set2 ' Copy the same elements in the ' Foo ' table, overwriting ' foo ' with the original content//srandmember returns 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 the increment and decrement of the index value of the specified element, changing the order of the Elements $redis->zincrby (' Zset1 ', ' Ten, ' ab ');//Return to 11//zrem Removes the specified element $redis->zrem (' Zset1 ', ' EF '); //true or false//zrange returns the elements of the specified interval in the table in 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 between the position 0 and the penultimate element (equivalent to all elements)// zrevrange , returns the element of the specified interval in the table, sequentially inverted $redis->zrevrange (' Zset1 ', 0,-1); //element order and Zrange opposite//zrangebyscore/zrevrangebyscore in order/ Descending returns the element of the specified index interval in the table $redis->zadd (' Zset1 ', 3, ' EF '), $redis->zadd (' Zset1 ', 5, ' GH '); $redis->zrangebyscore (' Zset1 ', 2,9); //returns the index value 2-9 between the elements array (' ef ', ' gh ')//Parameter form $redis->zrangebyscore (' Zset1 ', 2,9, ' withscores '); //returns the element between the index value 2-9 and contains the index value array (Array (' EF ', 3), array (' GH ', 5)) $redis->zrangebyscore (' Zset1 ', 2,9,array ( ' Withscores ' =>true, ' limit ' =>array (1, 2)); //returns the element between index value 2-9, ' Withscores ' => True to include the index value; ' limit ' =>array (1, 2), which indicates a maximum return of 2, with an array (array (' EF ', 3), array (' GH ', 5))//zunionstore/ zinterstore the set/intersection of multiple tables into another table $redis->zunionstore (' Zset3 ', Array (' Zset1 ', ' Zset2 ', ' zset0 ')); //will ' Zset1 ', ' Zset2 ', ' zset0 ' of the set deposit ' zset3 '//Other parameters $redis->zunionstore (' Zset3 ', Array (' Zset1 ', ' Zset2 '), array (' weights ') => array (5,0))); The//weights parameter represents a weight, in which the element that represents the sum after the value is greater than 5 is ranked before the $redis->zunionstore (' Zset3 ', Array (' Zset1 ', ' Zset2 '), Array (' aggregate ' => ' Max '),//' aggregate ' => ' max ' or ' min ' indicates that the same element is either a large value or a small value after the set is taken//zcount Counts the number of elements in an index interval $redis->zcount (' Zset1 ', 3,5);//2$redis->zcount (' Zset1 ', ' (3 ', 5)); //' (3 ') indicates that the index value is between 3-5 but not 3, Similarly, you can use the ' (5 ') Index of the $redis->zcard (' Zset1 ');//4//zscore query element with a maximum of 5 but no 5//zcard statistical elements (' Zset1 ', ' EF ');//3//zremrangebyscore delete an index interval element $redis->zremrangebyscore (' Zset1 ', 0,2); // Remove the index between 0-2 elements (' AB ', ' CD '), return the number of deleted elements 2//zrank/zrevrank return element in the table order/descending position (not the index) $redis->zrank (' Zset1 ', ' ef ');// Returns 0 because it is the first element; Zrevrank returns 1 (the last)//zremrangebyrank deletes the element $redis->zremrangebyrank (' Zset1 ', 0,10) of the specified position interval in the table; //deletes the element with position 0-10, returns the number of deleted elements 2 /**hash table operation *///hset/hget access to the hash table data $redis->hset (' Hash1 ', ' key1 ', ' v1 //the key as ' Key1 ' value for ' v1 ' elements into Hash1 table $redis->hset (' Hash1 ', ' key2 ', ' v2 '); $redis->hget (' Hash1 ', ' Key1 '); //remove the value of key ' Key1 ' in the table ' Hash1 ', return ' v1 '//hexists returns the presence of the specified key in the hash table $redis->hexists (' Hash1 ', ' key1 '); //true or false//hdel Delete the element $redis->hdel (' hash1 ', ' Key2 ') of the specified key in the hash table; //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 Access multiple elements to the hash table $redis->hmset (' Hash1 ', Array (' key3 ' = ' v3 ', ' key4 ' = ' v4 ')), $redis->hmget (' Hash1 ', Array (' Key3 ', ' Key4 ')); //returns the corresponding value array (' v3 ', ' v4 ')//hincrby the specified key to accumulate $redis->hincrby (' hash1 ', ' Key5 ', 3); //returns 3$redis->hincrby (' Hash1 ', ' Key5 ', ten); //returns 13//hkeys returns all Key$redis->hkeys in the hash table (' Hash1 '); //returns the array (' Key1 ', ' key2 ', ' Key3 ', ' key4 ', ' key5 ')//hvals returns all value$redis->hvals in the hash table (' Hash1 '); //returns the array (' v1 ', ' v2 ', ' v3 ', ' v4 ',//hgetall ') and returns the entire hash table element $redis->hgetall (' hash1 '); // Return Array (' key1 ' = ' v1 ', ' key2 ' = ' v2 ', ' key3 ' = ' v3 ', ' key4 ' = ' v4 ', ' Key5 ' =>13)/** sort operations *///sort sort $ Redis->rpush (' tab ', 3); $redis->rpush (' tab ', 2), $redis->rpush (' tab ', '), $redis->sort (' tab '), //returns an array (2,3,17)//Using parameters, Can be combined with array (' sort ' => ' desc ', ' Limit ' => array (1, 2)) $redis->sort (' tab ', Array (' sort ' => ' desc '); //in descending order, returning 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), and returns an array (3,17) $redis->sort (' tab ', Array (' Limit ' => array (' alpha ' => true)); //returns an array (17,2,3) sorted by first character, Because the first character of 17 is ' 1 ' so the first row of $redis->sort (' tab ', Array (' Limit ' => array (' store ' => ' ordered ') )); //represents a permanent sort, returning the number of elements $redis->sort (' tab ', Array (' Limit ' => array (' Get ' => ' pre_ * ')); //uses the wildcard character ' * ' to filter elements, indicating that only elements beginning with ' pre_ ' are returned/**REDIS administrative operations *///select Specify the database $redis->select (' MyDB ') to be manipulated; //specified as MyDB, does not exist then creates//flushdb empties the current library $redis->flushdb ();//move move the elements of the library to other libraries $redis->set (' foo ', ' Bar '); $redis->move (' foo ', ' mydb2 '); //if ' MYDB2 ' inventory is displayed in//info service when status information $redis->info ();//slaveof configuration from server $redis- >slaveof (' 127.0.0.1 '); //Configure the server for 127.0.0.1 Port 80 to be from server $redis->slaveof (); //clear from server//Synchronize Save server data to disk $ Redis->save ();//Asynchronously Save the 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); //stores multiple keys corresponding to value$retval = $redis->mget (Array_keys ($mkv)); // Get Valueprint_r ($retval) for 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 Operations Function zpop ($client, $zsetKey) { $element = null; $options = array ( ' CAs ' => true, // initialize with support for CAS operations ' Watch ' = > $zsetKey, // key that needs to be watched to detect changes ' Retry ' => 3, // number of retries on aborted transactions, after // which the client bails out with 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* be 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 ( array ( ' host ' => ' 127.0.0.1 ', ' Port ' => 6379, ' database ' => 15, ' Alias ' => ' first ', ), array ( ' host ' => ' 127.0.0.1 ', ' Port ' => 6380, ' database ' => 15, ' Alias ' => ' second ', ); 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++; } public function&Nbsp;remove ($node) { $this->_nodes = array_ Filter ($this->_nodes, function ($n) use ($node) { return $n !== $node; &NBSP); $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 ();p rintf ("server '%s ' has %d keys while server '%s ' has %d keys.\n ", ' first ', $server 1[' db15 ' [' Keys '], ' second ', $server 2[' db15 ' [' Keys ']);
Predis Operation Daquan