Use AutoLoad to load the relevant library, this is the key torequire$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 ' = +); $redis = new C Lient ($server);//General Set/get Operation $redis->set (' Library ', ' Predis '); $retval = $redis->get (' library '); Echo $retval; Show ' Predis '//setex set a storage aging $redis->setex (' str ', ' 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 replacement $redis->getset (' foo ', 56);//return 34//INCRBY/INCR/DECRBY/DECR increment and decrement values $redis- >INCR (' foo '); Foo is 57$redis->incrby (' foo ', 2); Foo detects if there is a value $redis->exists (' foo ') for 59//exists,//true//del deletes $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, return None$redis->set (' str ', ' Test ') ; $redis->type (' str '); String that returns String//append connected to the already existing string $redis->append (' str ', ' _123′ '); Returns the cumulative string length of 8, this input str for the ' Test_123′//setrange part replacement Operation $redis->setrange (' str ', 0, ' abc '); Returns 3, Parameter 2 is 0 o'clock equivalent to SET operation $redis->setrange (' str ', 2, ' CD ');//return 4, indicating the replacement from the 2nd word specifier, when ' str ' is ' ABCD '//substr partial get Operation $redis->substr (' str ', 0,2 );//Represents the 2nd character from the No. 0, a total of 3, return ' ABC '//strlen get the string length $redis->strlen (' str '); Return 4//setbit/getbit bit storage and get $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 feature, which supports the * number and the (match one character) $redis->set (' foo1′,123); $redis->set (' foo2′,456 '); $redis->keys (' foo* ') ); Returns the Array$redis->keys of Foo1 and Foo2 (' 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, but the difference is that Renamenx is not allowed to change to an existing key$redis->rename (' Str ', ' str2′ '); The original named ' str ' was changed to ' Str2′//expire set Key-value's timeliness, TTL to obtain the remaining period of validity, persist reset to permanent storage $redis->expire (' foo ', 1); The setting is 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 ();/*QueueOperation *///rpush/rpushx ordered list operation, fromQueueAfter inserting elements//lpush/lpushx and rpush/rpushx the difference is inserted into theQueueThe head, IBID., ' x ' means to operate only on the existing key $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 for existingQueueDo add, otherwise return 0//llen returns the current list length $redis->llen (' foolist ');//3//lrange returnsQueueThe element $redis->lrange in an interval (' 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; Back to ' Bar1′//lset modifiedQueueValue$redis->lset in the specified position (' Foolist ', 1, ' 123′);//Modify the element of position 1, return True//lrem DeleteQueueA specified number of characters $redis->lrem (' Foolist ', 1, ' _ ') from the left; DeleteQueueFrom the left (use-1) 1 characters ' _ ' (if any)//lpop/rpop similar stack structure to pop (and delete) the leftmost or most right element $redis->lpop (' foolist '); ' bar0′ $redis->rpop (' foolist '); ' Bar2′//ltrimQueueModify, leave several elements on the left, and the rest delete $redis->ltrim (' foolist ', 0,1); Keep the No. 0 to 1th element from the left//rpoplpush from aQueuePop out of the element and push to anotherQueue$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′ ');//also applies to the sameQueue, move the last element to the head list2 =>array (' ab3′, ' ab1′, ' ab2′ ')//linsert inQueueThe middle of the specified element before or after inserting elements $redis->linsert (' list2′, ' before ', ' ab1′, ' 123′ '); The expression is inserted before the element ' ab1′ ' 123′ $redis->linsert (' list2′, ' after ', ' ab1′, ' 456′ '); Indicates that after the element ' ab1′ is inserted ' 456′//blpop/brpop blocks and waits for a queue to not be empty, then pops out the leftmost or most right element (this function can be said to be very useful outside 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, and after 10 seconds the timeout/**set table operation *///sadd add element, return True, return False$redis->sadd (' set1′, ' ab ') repeatedly; $ Redis->sadd (' set1′, ' CD '); $redis->sadd (' set1′, ' ef ');//srem remove the specified element $redis->srem (' set1′, ' CD '); Remove the ' CD ' element//spop popup first element $redis->spop (' set1′);//smove move 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 number $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 the array (' AB ')//sinterstore/Sunionstore/sdiffstore Copy 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 ' foo ' table, overwriting ' foo ' original content//srandmember return a random element $redis->srandmember (' set1′ ') in the table;/** 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 to the specified elementIndexThe value increases or decreases, changing the order of the Elements $redis->zincrby (' zset1′,10, ' ab ');//Returns 11//ZREM removes the specified element $redis->zrem (' zset1′, ' ef '); True or False//zrange returns the element $redis->zrange (' zset1′,0,1) of the specified interval in the table in position order; 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 opposite//zrangebyscore/zrevrangebyscore in order/descending return table specifiedIndexThe elements of the interval $redis->zadd (' zset1′,3, ' ef '); $redis->zadd (' zset1′,5, ' gh '); $redis->zrangebyscore (' zset1′,2,9 '); ReturnIndexA value of 2-9 elements between array (' EF ', ' gh ')//Parameter form $redis->zrangebyscore (' zset1′,2,9, ' withscores '); ReturnIndexThe element between value 2-9 and containsIndexThe value array (' EF ', 3), array (' GH ', 5)) $redis->zrangebyscore (' Zset1′,2,9,array (' withscores ' =>true, ' limit ' = >array (1, 2)); ReturnIndexThe element between the value 2-9, ' Withscores ' =>true represents the containingIndexValue ' 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′ '); Set the ' zset1′, ' zset2′, ' zset0′ ' to ' zset3′//other parameters $redis->zunionstore (' Zset3′,array ' (' zset1′, ' zset2′ '), Array (' Weights ' = = Array (5,0))); The//weights parameter represents a weight, which indicates that the element with the value greater than 5 after the sum is in front of the row, greater than 0, after $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 statistics aIndexThe number of elements in the interval $redis->zcount (' zset1′,3,5 ');//2$redis->zcount (' zset1′, ' (3′,5)); ' (3′ saidIndexThe value is between 3-5 but not 3, so you can use ' (5′ for a maximum of 5 but not 5//zcard $redis->zcard (' zset1′),//4//zscore query elementIndex$redis->zscore (' zset1′, ' ef ');//3//zremrangebyscore Delete aIndexelement of the interval $redis->zremrangebyscore (' zset1′,0,2); DeleteIndexThe element between 0-2 (' AB ', ' CD '), returns the number of deleted elements 2//zrank/zrevrank returns the table order/descending position of the element (notIndex) $redis->zrank (' zset1′, ' ef ');//returns 0 because it is the first element; Zrevrank returns 1 (the last)//zremrangebyrank deletes the element in the specified position range in the table $redis-> Zremrangebyrank (' zset1′,0,10); Delete the element with position 0-10, return the number of deleted elements 2/**hash table operation *///hset/hget Access hash table Data $redis->hset (' hash1′, ' key1′, ' v1′); Save key as ' Key1′value ' v1′ elements into 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 presence of the specified key in the hash table for $redis->hexists (' hash1′, ' key1′ '); True or False//hdel removes 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 of the array (' v3′, ' v4′)//hincrby the specified key to accumulate $redis->hincrby (' hash1′, ' key5′,3); Return to 3$redis->hincrby (' hash1′, ' key5′,10); 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 an array (' v1′, ' v2′, ' v3′, ' v4′,13 ')//hgetall returns the entire hash table element $redis->hgetall (' hash1′ '); Returns the 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 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 returns an array (17,2,3), because the first character of 17 is ' 1′ so the top of the line is $redis->sort (' tab ', Array (' ' limit ' = ' = ' = ' ordered ') )); Represents a permanent sort, returning the number of elements $redis->sort (' tab ', Array (' limit ' = = ' Array (' get ' = = ' pre_* ')); A wildcard ' * ' filter element is used to return only elements that begin with ' pre_ '/**redis management operations *///select Specify the database to be manipulatedEdis->select (' mydb '); Specified as MyDB, does not exist create//flushdb empty the current library $redis->flushdb ();//move moves the elements of the library to other libraries $redis->set (' foo ', ' Bar '); $redis Move (' foo ', ' mydb2′ '); If ' mydb2′ inventory is displayed in//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 be $redis->slaveof from the server (); Clear from server//sync save server data to disk $redis->save ();//Asynchronously Save 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 Valueprint_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 ', (); $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 to is watched to detect changes ' retry ' = 3,//number of retries on aborted t Ransactions, 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* 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: '));///Distributed storage methods $multiple_servers = Array (' host ' = ' 127.0.0.1′, ' port ' = 6 379, ' database ' = +, ' Alias ' = ' first ', ', ' Array (' host ' = ' 127.0.0.1′ ', ' port ' = = 6380, ' database ' =&G T ' Alias ' = ' second ',), and 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++;} 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 ', $server 2[' d B15 ' [' Keys ']
The above describes the basic use of Redis in PHP, including require, queue, Exception, index content, I hope that the PHP tutorial interested in a friend helpful.