Basic use cases of redis in PHP and redisPHP. The basic use cases of redis in PHP, and the use cases of redisPHP download www. oschina. after netpredis is decompressed, it contains the lib source file, examples example, and test the basic use case of copying the lib directory to redis in PHP. redisPHP use case
Download http://www.oschina.net/p/redis
Decompress the package, including the lib source file, examples example, and test.
Copy the lib directory to your project to start your predis operation.
// Use autoload to load the relevant database. 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 address, port, and database
$ Server = array (
'Host' => '2017. 0.0.1 ′,
'Port' => 6379,
'Database' => 15
);
$ Redis = new Client ($ server );
// Normal set/get operation
$ Redis-> set ('Library ', 'predis ');
$ Retval = $ redis-> get ('Library ');
Echo $ retval; // Display 'predis'
// Setex set a storage validity period
$ Redis-> setex ('str', 10, 'bar'); // indicates that the storage is valid for 10 seconds.
// Setnx/msetnx is equivalent to the add operation and does not overwrite existing values.
$ Redis-> setnx ('foo', 12); // true
$ Redis-> setnx ('foo', 34); // false
// Getset operation, a variant of set. The result returns the value before replacement.
$ Redis-> getset ('foo', 56); // 34 is returned.
// Incrby/incr/decrby/decr increment and decrease
$ Redis-> incr ('Foo'); // foo is 57
$ Redis-> incrby ('foo', 2); // foo is 59
// Exists checks whether a value exists.
$ Redis-> exists ('Foo'); // true
// Delete del
$ Redis-> del ('Foo'); // true
// Type detection, string return string, list return list, set table return set/zset, hash table return hash
$ Redis-> type ('Foo'); // if no value exists, none is returned.
$ Redis-> set ('str', 'test ');
$ Redis-> type ('str'); // string, return string
// Append connection to an existing string
$ Redis-> append ('str', '_ 123'); // return the accumulated string length of 8, which is 'test _ 123 ′
// Setrange partial replacement
$ Redis-> setrange ('str', 0, 'ABC'); // returns 3. if parameter 2 is 0, it is equivalent to the set operation.
$ Redis-> setrange ('str', 2, 'CD'); // returns 4, which indicates that the value is replaced after 2nd characters. then, 'str' is 'ABCD'
// Substr partial acquisition operation
$ Redis-> substr ('str', 0th); // it indicates that it starts from 2nd and takes characters, 3 in total. 'ABC' is returned'
// Obtain the string length by strlen
$ Redis-> strlen ('str'); // 4 is returned.
// Setbit/getbit storage and retrieval
$ Redis-> setbit ('binary ', 31,1); // indicates storing 1 in 31st bits. Is there a problem with the size? But it doesn't matter. getbit should be okay.
$ Redis-> getbit ('binary ', 31); // return 1
// The keys fuzzy search function supports the * and? (Match one character)
$ Redis-> set ('foo1', 123 );
$ Redis-> set ('foo2', 456 );
$ Redis-> keys ('foo * '); // returns the array of foo1 and foo2
$ Redis-> keys ('F? O? '); // Same as above
// Randomkey returns a random key
$ Redis-> randomkey (); // it may return 'foo1' or 'foo2' and any other key with redis
// Rename/renamenx rename the key. The difference is that renamenx cannot be changed to an existing key.
$ Redis-> rename ('str', 'str2'); // change the key originally named 'str' to 'str2 ′
// Expire sets the key-value validity period, ttl gets the remaining validity period, and persist is reset to permanent storage.
$ Redis-> expire ('foo', 1); // Set the validity period to 1 second.
$ Redis-> ttl ('Foo'); // returns the validity period of 1 s.
$ Redis-> expire ('Foo'); // cancel the expire action
// Dbsize returns the total number of records of the current redis database
$ Redis-> dbsize ();
/*
Queue operations
*/
// Rpush/rpushx ordered list operation, insert elements from the queue
// The difference between lpush/lpushx and rpush/rpushx is that it is inserted into the queue header. the same as above, 'x' indicates that only the existing key is operated.
$ Redis-> rpush ('foolist', 'bar1'); // return the length of a list of 1
$ Redis-> lpush ('foolist', 'bar0'); // returns the length of a list of 2
$ Redis-> rpushx ('foolist', 'bar2'); // 3 is returned. rpushx only adds existing queues; otherwise, 0 is returned.
// Llen returns the length of the current list
$ Redis-> llen ('foolist'); // 3
// Lrange returns the element of a range in the queue.
$ Redis-> lrange ('foolist', 0th); // The Returned array contains 1st to elements in total.
$ Redis-> lrange ('foolist', 0,-1); // returns the first to the last, which is equivalent to returning all elements. Note that a negative number is often used in redis, same below
// Lindex returns the list element at the specified sequence.
$ Redis-> lindex ('foolist', 1); // return 'bar1 ′
// Lset modifies the value at the specified position in the queue
$ Redis-> lset ('foolist', 1, '000000'); // modify the element at location 1 and return true
// Lrem deletes the specified number of characters from the left of the queue.
$ Redis-> lrem ('foolist', 1, '_'); // delete the left of the queue (use-1 from the right) 1 Character '_' (if any)
// Lpop/rpop pops up (and deletes) the leftmost or rightmost element similar to the stack structure.
$ Redis-> lpop ('foolist'); // 'bar0 ′
$ Redis-> rpop ('foolist'); // 'bar2 ′
// Modify the ltrim queue, retain several elements on the left, and delete the remaining elements.
$ Redis-> ltrim ('foolist', 0th); // retain 1st to elements on the left
// Rpoplpush outputs elements from one queue pop and pushes them to another queue
$ Redis-> rpush ('list1', 'ab0 ′);
$ Redis-> rpush ('list1', 'ab1 ′);
$ Redis-> rpush ('list2', 'ab2 ′);
$ Redis-> rpush ('list2', 'ab3 ′);
$ Redis-> rpoplpush ('list1', 'list2'); // result list1 => array ('ab0'), list2 => array ('ab1 ′, 'ab2', 'ab3 ′)
$ Redis-> rpoplpush ('list2', 'list2'); // It is also applicable to the same queue. move the last element to the header list2 => array ('ab3 ′, 'ab1', 'ab2 ′)
// Linsert inserts an element before or after the specified element in the queue
$ Redis-> linsert ('list2', 'before', 'ab1', '000000'); // inserts '000000' before the element 'ab1 ′
$ Redis-> linsert ('list2', 'after', 'ab1', '000000'); // inserts '000000' after the element 'ab1 ′
// Blpop/brpop blocking and waiting for a queue not empty, pop out the leftmost or rightmost element (this function can be very useful outside php)
// Brpoplpush is also blocked and waits for the operation. The result is the same as rpoplpush.
$ Redis-> blpop ('list3', 10); // If list3 is empty, wait until the first element pops up when it is not empty and times out after 10 seconds
/**
Set Table operations
*/
// Add an element to sadd. true is returned. false is returned for repeated operations.
$ Redis-> sadd ('set1', 'AB ');
$ Redis-> sadd ('set1', 'CD ');
$ Redis-> sadd ('set1', 'ef ');
// Srem removes the specified element
$ Redis-> srem ('set1', 'CD'); // delete the 'CD' element
// Spop pops up the first element
$ Redis-> spop ('set1 ′);
// Smove moves the specified element of the current set table to another set table
$ Redis-> sadd ('set2', '000000 ′);
$ Redis-> smove ('set1', 'set2', 'AB'); // move 'AB' in 'set1' to 'set2', and return true or false
// Scard returns the number of elements in the current set table
$ Redis-> scard ('set2'); // 2
// Sismember determines whether the element belongs to the current table
$ Redis-> sismember ('set2', '000000'); // true or false
// Smembers returns all elements of the current table
$ Redis-> smembers ('set2'); // array ('000000', 'AB ');
// Sinter/sunion/sdiff returns the intersection of elements in the two tables/Union/complement set
$ Redis-> sadd ('set1', 'AB ');
$ Redis-> sinter ('set2', 'set1'); // returns array ('AB ')
// Sinterstore/sunionstore/sdiffstore copy the intersection/Union/complementary set elements of the two tables to the third table
$ Redis-> set ('foo', 0 );
$ Redis-> sinterstore ('foo', 'set1'); // The content of 'set1' is copied to 'foo, convert 'foo' to the set table.
$ Redis-> sinterstore ('foo', array ('set1', 'set2 ′)); // copy the same elements in 'set1' and 'set2' to the 'foo' table to overwrite the original content of 'foo '.
// Srandmember returns a random element in the table
$ Redis-> srandmember ('set1 ′);
/**
Ordered set table operation
*/
// Add an element to sadd and set the sequence number. true is returned. false is returned if the number is repeated.
$ Redis-> zadd ('zset1', 1, 'AB ');
$ Redis-> zadd ('zset1', 2, 'CD ');
$ Redis-> zadd ('zset1', 3, 'ef ');
// Zincrby increases or decreases the index value of a specified element and changes the order of elements
$ Redis-> zincrby ('zset1', 10, 'AB'); // return 11
// Zrem remove the specified element
$ Redis-> zrem ('zset1', 'ef '); // true or false
// Zrange returns the elements of the specified range in the table in order of position
$ Redis-> zrange ('zset1',); // returns an element between 0 and 1.
$ Redis-> zrange ('zset1', 0,-1); // returns the element between position 0 and the last element (equivalent to all elements)
// Zrevrange is the same as above. Elements of the specified range in the table are returned in reverse order.
$ Redis-> zrevrange ('zset1', 0,-1); // The element sequence is opposite to zrange.
// Zrangebyscore/zrevrangebyscore returns the elements of the specified index range in the table in order/in descending order.
$ Redis-> zadd ('zset1', 3, 'ef ');
$ Redis-> zadd ('zset1', 5, 'gh ');
$ Redis-> zrangebyscore ('zset1',); // returns the array ('ef ', 'gh') element between 2-9 index values ')
// Parameter format
$ Redis-> zrangebyscore ('zset1', 'withscores'); // returns the elements between the index value and the index value array ('ef ', 3), array ('GH', 5 ))
$ Redis-> zrangebyscore ('zset1', 2,9, array ('withscores' => true, 'limit' => array (1, 2 ))); // return the elements between the index value and 2-9. 'withscores' => true indicates that the index value is included; 'limit' => array (1, 2) indicates that up to 2 items are returned, the result is array ('ef ', 3), array ('GH', 5 ))
// Zunionstore/zinterstore store the Union/intersection of multiple tables into another table
$ Redis-> zunionstore ('zset3', array ('zset1', 'zset2', 'zset0'); // Set 'zset1', 'zset2 ′, the Union of 'zset0' is stored in 'zset3 ′
// Other parameters
$ Redis-> zunionstore ('zset3', array ('zset1', 'zset2'), array ('weight' => array (5, 0 ))); // The weights parameter indicates the weight, which indicates that elements with a union value greater than 5 are ranked first, and those with a value greater than 0 are ranked later.
$ Redis-> zunionstore ('zset3', array ('zset1', 'zset2'), array ('aggregat' => 'Max ')); // 'aggregate' => 'Max 'or 'min' indicates that the same element after the union is used to take the Iterator or a small value.
// Zcount counts the number of elements in an index range.
$ Redis-> zcount ('zset1', 3,5); // 2
$ Redis-> zcount ('zset1', '(3', 5); //' (3' indicates that the index value ranges from 3 to 5, but does not include 3, similarly, you can use '(5' indicates that the upper limit is 5 but not 5.
// Zcard count
$ Redis-> zcard ('zset1'); // 4
// Index of the zscore query element
$ Redis-> zscore ('zset1', 'ef '); // 3
// Zremrangebyscore deletes the element of an index range.
$ Redis-> zremrangebyscore ('zset1',); // delete the elements between 0-2 ('AB', 'CD'), and return the number of deleted elements 2
// Zrank/zrevrank returns the order of the table in which the elements are located/the position in descending order (not an index)
$ Redis-> zrank ('zset1', 'ef '); // returns 0 because it is the first element; zrevrank returns 1 (the last one)
// Zremrangebyrank deletes the elements in the specified position range in the table.
$ Redis-> zremrangebyrank ('zset1',); // delete an element with a position of 0 to 10. the number of deleted elements is 2.
/**
Hash table operations
*/
// Hset/hget to access the data in the hash table
$ Redis-> hset ('hash1', 'key1', 'v1 '); // store the elements whose key is 'key1' value is 'v1' to the hash1 table.
$ Redis-> hset ('hash1', 'key2', 'V2 ′);
$ Redis-> hget ('hash1', 'key1'); // retrieves the value of 'key1' in 'hash1' and returns 'V1 ′
// Hexists returns whether the specified key in the hash table exists
$ Redis-> hexists ('hash1', 'key1'); // true or false
// Hdel delete the elements 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
// Add an element to hsetnx, but it cannot be repeated.
$ Redis-> hsetnx ('hash1', 'key1', 'V2'); // false
$ Redis-> hsetnx ('hash1', 'key2', 'V2'); // true
// Hmset/HMET access multiple elements to the hash table
$ Redis-> hmset ('hash1', array ('key3' => 'v3 ', 'key4' => 'V4 ′));
$ Redis-> HMET ('hash1', array ('key3', 'key4'); // returns the corresponding value array ('v3 ', 'V4 ′)
// Hincrby accumulates the specified key
$ Redis-> hincrby ('hash1', 'key5', 3); // 3 is returned.
$ Redis-> hincrby ('hash1', 'key5', 10); // return 13
// Hkeys returns all keys in the hash table
$ Redis-> hkeys ('hash1'); // return array ('key1', 'key2', 'key3', 'key4', 'key5 ′)
// Hvals returns all values in the hash table
$ Redis-> hvals ('hash1'); // return array ('v1 ', 'V2', 'v3', 'V4 ', 13)
// Hgetall returns the entire hash table element
$ Redis-> hgetall ('hash1'); // returns an array ('key1' => 'v1 ', 'key2' => 'V2 ′, 'key3' => 'v3 ', 'key4' => 'V4', 'key5' => 13)
/**
Sort operation
*/
// Sort
$ Redis-> rpush ('Tab ', 3 );
$ Redis-> rpush ('Tab ', 2 );
$ Redis-> rpush ('Tab ', 17 );
$ Redis-> sort ('Tab '); // returns array (2, 3, 17)
// Use parameters. you can use array ('sort '=> 'desc', 'Limit' => array (1, 2) in combination ))
$ Redis-> sort ('Tab ', array ('sort' => 'desc'); // returns array (, 2) in descending order)
$ Redis-> sort ('Tab ', array ('limit' => array (1, 2 ))); // returns two elements of 1 in the ordered position (2 here refers to the number, not the position), and returns array)
$ Redis-> sort ('Tab ', array ('limit' => array ('alpha' => true); // returns array (17,2, 3) because the first character of 17 is '1 ',
$ Redis-> sort ('Tab ', array ('limit' => array ('store' => 'ordered'); // indicates permanent sorting and returns the number of elements.
$ Redis-> sort ('Tab ', array ('limit' => array ('get' => 'pre _*'))); // use the wildcard '*' to filter elements, indicating that only elements starting with 'pre _ 'are returned.
/**
Redis management operations
*/
// Select specifies the database to operate
$ Redis-> select ('mydb'); // it is specified as mydb. if it does not exist, it is created.
// Flushdb clears the current database
$ Redis-> flushdb ();
// Move the elements of the database to other databases
$ Redis-> set ('foo', 'bar ');
$ Redis-> move ('foo', 'mydb'); // If 'mydb' is in stock
// Info displays service status information
$ Redis-> info ();
// Slaveof configuration slave server
$ Redis-> slaveof ('127. 0.0.1 ', 80); // The server configured with Port 80 127.0.0.1 is a slave server
$ Redis-> slaveof (); // clear the slave server
// Synchronously save server data to disk
$ Redis-> save ();
// Asynchronously save server data to disk
$ Redis-> bgsave ();
//??
$ Redis-> bgrewriteaof ();
// Returns the last disk update time.
$ Redis-> lastsave ();
// Set/get multiple key-values
$ Mkv = array (
'Usr: 0001 '=> 'first user ',
'Usr: 0002 '=> 'second user ',
'Usr: 0003 '=> 'third user'
);
$ Redis-> mset ($ mkv); // store values corresponding to multiple keys
$ Retval = $ redis-> mget (array_keys ($ mkv); // obtain the value corresponding to multiple keys
Print_r ($ retval );
// Batch 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 ";
// Add a prefix to the access key, for example, 'nrk :'
$ Redis-> getProfile ()-> setPreprocessor (new KeyPrefixPreprocessor ('nrk :'));
// Some distributed storage methods
$ Multiple_servers = array (
Array (
'Host' => '2017. 0.0.1 ′,
'Port' => 6379,
'Database' => 15,
'Alias' => 'first ',
),
Array (
'Host' => '2017. 0.0.1 ′,
'Port' => 6380,
'Database' => 15,
'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 ++;
}
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 );
}
}
// Configure the 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 ");
}
$ Server1 = $ redis-> getClientFor ('first')-> info ();
$ Server2 = $ redis-> getClientFor ('second')-> info ();
Printf ("Server '% s' has % d keys while server' % s' has % d keys. \ n ",
'First', $ server1 ['db15'] ['Keys '], 'second', $ server2 ['db15'] ['Keys']
How can php redis respond?
Redis stores data in the memory and loses power. Pay attention to this. make a persistence if necessary. The persistence method is hard to understand. For more information, see the article on the Internet.
Php's redis extension is called php-redis. The php-redis Chinese manual is available on the internet. The following is an example:
Connect ('2017. 0.0.1 ', 6379); // 6379 is the default port $ result = $ redis-> set ('123', "comment "); // set the key value echo $ result = $ redis-> get ('20140901'); // get the key value $ all = $ redis-> getMultiple (array ('20140901 ', '9639002718'); // obtain multiple key values at the same time // The method for obtaining all key values is not provided. I'm not sure whether it can be used. you can give it a try. $ All = $ redis-> getMultiple (array ('*'));
Thank you for your support!
How can I determine whether redis is suspended when php is connected to Redis?
Ping redis command
Unzip download http://www.oschina.net/p/redis decompress there are: lib source file, examples example, test to copy the lib directory...