The basic use of Redis in PHP

Source: Internet
Author: User
Tags cas crc32 redis

// Use autoload to load related libraries, the point 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);


// Ordinary 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’); // Indicates that the storage period is 10 seconds


// setnx / msetnx is equivalent to add operation and will not overwrite the existing value

$ 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); // return 34


// incrby / incr / decrby / decr increments and decrements the value

$ redis-> incr (‘foo’); // foo is 57

$ redis-> incrby (‘foo’, 2); // foo is 59


// exists detect whether a value exists

$ redis-> exists (‘foo’); // true


// del delete

$ redis-> del (‘foo’); // true


// type type detection, string returns string, list returns list, set table returns set / zset, hash table returns hash

$ redis-> type (‘foo’); // None, return none

$ redis-> set (‘str’, 'test ’);

$ redis-> type (‘str’); // string, return string


// append connect to the existing string

$ redis-> append (‘str’, '_ 123 ′); // Return to the accumulated string length 8, the input str is ‘test_123’


// setrange partial replacement operation

$ redis-> setrange (‘str’, 0, ’abc’); // Return 3, when parameter 2 is 0, it is equivalent to set operation

$ redis-> setrange (‘str’, 2, ’cd’); // Return 4, it means to replace after the second character, then ‘str’ is ‘abcd’


// Substr part get operation

$ redis-> substr (‘str’, 0,2); // Indicating that from the 0th, get the 2nd character, a total of 3, return ‘abc’


// strlen gets the length of the string

$ redis-> strlen (‘str’); // Return 4


// setbit / getbit bit storage and retrieval

$ redis-> setbit (‘binary’, 31,1); // Indicating that 1 is stored in the 31st bit, there may be big and small issues here?

$ redis-> getbit (‘binary’, 31); // Return 1


// Keys fuzzy search function, support * and? (match a character)

$ redis-> set (‘foo1’, 123);

$ redis-> set (‘foo2’, 456);

$ redis-> keys (‘foo *’); // Return an array of foo1 and foo2

$ redis-> keys (‘f? o?’); // Same as above


// randomkey returns a key randomly

$ redis-> randomkey (); // May be to return ‘foo1’ or ‘foo2’ and any other key that exists in redis


// rename / renamenx rename the key, the difference is that renamenx is not allowed to change to an existing key

$ redis-> rename (‘str’, ’str2’); // Change the key originally named ‘str’ to ‘str2’


// expire sets the timeliness of key-value, 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’); // Return valid period value 1s

$ redis-> expire (‘foo’); // Cancel expire behavior


// dbsize returns the total number of records in redis current database

$ redis-> dbsize ();


/ *

Queue operation

* /


// 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 head of the queue. As above, ‘x’ means only operate on the existing key

$ redis-> rpush (‘fooList’, ‘bar1’); // Return the length of a list 1

$ redis-> lpush (‘fooList’, ‘bar0’); // Return the length of a list 2

$ redis-> rpushx (‘fooList’, ‘bar2’); // Return 3, rpushx only adds to the existing queue, otherwise it returns 0

// llen returns the current list length

$ redis-> llen (‘fooList’); // 3


// lrange returns the elements of a range in the queue

$ redis-> lrange (‘fooList’, 0,1); // The returned array contains the 0th to the first 2 elements

$ redis-> lrange (‘fooList’, 0, -1); // Return the 0th to the first to last, equivalent to returning all the elements


// lindex returns the list element at the specified order

$ redis-> lindex (‘fooList’, 1); // Return to ‘bar1’


// lset modify the value at the specified position in the queue

$ redis-> lset (‘fooList’, 1, ’123 ′); // Modify the element at position 1, return true


// lrem deletes the specified number of characters from the left in the queue

$ redis-> lrem (‘fooList’, 1, ’_ '); // Delete 1 character from the left in the queue (use -1 from the right)’ _' (if any)


// lpop / rpop pops (and deletes) the leftmost or rightmost element like a stack structure

$ redis-> lpop (‘fooList’); // ’bar0’

$ redis-> rpop (‘fooList’); // ’bar2’


// Modify the ltrim queue, keep some elements from the left, delete the rest

$ redis-> ltrim (‘fooList’, 0,1); // Retain the 0th to 1st element from the left


// rpoplpush pops elements from one queue and pushes 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 ′); // also applies to the same queue, move the last element to the head list2 => array (‘ ab3 ’,’ ab1 ′, ’ab2 ′)


// linsert inserts elements before or after the specified element in the middle of the queue

$ redis-> linsert (‘list2’, ‘before’, ’ab1’, ’123’); // indicates that ‘123’ is inserted before the element ‘ab1’

$ redis-> linsert (‘list2’, ‘after’, ’ab1’, ’456’); // Indicates inserting ‘456’ after element ‘ab1’


// blpop / brpop blocks and waits for a queue that is not empty, then pops the leftmost or rightmost element (this function can be said to be very useful outside of php)

// brpoplpush is also blocking and waiting for operation, the result is the same as rpoplpush

$ redis-> blpop (‘list3’, 10); // If list3 is empty, wait until the first element is popped when it is not empty, timeout after 10 seconds


/ **

set table operation

* /


// sadd adds elements, returns true, repeatedly returns false

$ redis-> sadd (‘set1’, ’ab’);

$ redis-> sadd (‘set1’, ’cd’);

$ redis-> sadd (‘set1’, ’ef’);


// srem remove the specified element

$ redis-> srem (‘set1’, ’cd’); // Remove the ‘cd’ element


// spop pops the 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 the ‘ab’ from ‘set1’ to ‘set2’, return true or false


// scard returns the number of elements in the current set table

$ redis-> scard (‘set2’); // 2


// sismember judges 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 / union / complement of the elements in the two tables

$ redis-> sadd (‘set1’, ’ab’);

$ redis-> sinter (‘set2 ′,’ set1 ′); // Return array (‘ab’)


// sinterstore / sunionstore / sdiffstore copies the intersection / union / complementary elements of the two tables into the third table

$ redis-> set (‘foo’, 0);

$ redis-> sinterstore (‘foo’, ’set1’); // This is equivalent to copying the contents of ‘set1’ into ‘foo’, and converting ‘foo’ into the set table

$ redis-> sinterstore ('foo', array ('set1', 'set2')); // Copy the same elements in 'set1' and 'set2' to the table of 'foo', overwriting the original of 'foo' content


// srandmember returns a random element in the table

$ redis-> srandmember (‘set1’);


/ **

Ordered set table operation

* /


// sadd adds elements, and sets the sequence number, returns true, repeatedly returns false

$ redis-> zadd (‘zset1 ′, 1,’ ab ’);

$ redis-> zadd (‘zset1’, 2, ’cd’);

$ redis-> zadd (‘zset1 ′, 3,’ ef ’);


// zincrby increases or decreases the index value of the specified element and changes the arrangement order of the elements

$ redis-> zincrby (‘zset1’, 10, ’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); // Return the element between position 0 and 1 (two)

$ redis-> zrange (‘zset1’, 0, -1); // Return the element between position 0 and the first element from the bottom (equivalent to all elements)


// zrevrange Same as above, return the elements of the specified range in the table, in reverse order

$ redis-> zrevrange (‘zset1’, 0, -1); // The order of elements is opposite to zrange


// zrangebyscore / zrevrangebyscore returns the elements of the specified index range in the table in order / descending order

$ redis-> zadd (‘zset1 ′, 3,’ ef ’);

$ redis-> zadd (‘zset1 ′, 5,’ gh ’);

$ redis-> zrangebyscore (‘zset1’, 2,9); // Return the element array between index values 2-9 (‘ef’, 'gh ’)

// Parameter form

$ redis-> zrangebyscore ('zset1 ′, 2,9,' withscores '); // Return elements between index values 2-9 and contain index values array (array (' ef ', 3), array (' gh ', 5))

$ redis-> zrangebyscore ('zset1 ′, 2,9, array (' withscores' => true, 'limit' => array (1, 2))); // Return elements between index values 2-9, 'withscores' => true means to include the index value; 'limit' => array (1, 2), means to return up to 2 results, the result is array (array ('ef', 3), array ('gh', 5) )


// zunionstore / zinterstore stores the union / intersection of multiple tables in another table

$ redis-> zunionstore (‘zset3 ′, array (‘ zset1 ′, ’zset2 ′,’ zset0 ′)); // store the union of ‘zset1 ′,’ zset2 ′, ’zset0 ′ into‘ zset3 ’

//Other parameters

$ redis-> zunionstore ('zset3 ′, array (' zset1 ′, 'zset2 ′), array (' weights' => array (5,0))); // The weights parameter represents the weight, which represents the value after union Elements greater than 5 come first, and elements greater than 0 come after

$ redis-> zunionstore ('zset3 ′, array (' zset1 ′, 'zset2 ′), array (' aggregate '=>' max ')); //' aggregate '=>' max 'or' min 'means and The same element after the set is to take a large value or take a small value


// zcount counts 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 does not contain 3, the same can also use' (5 ′ means the upper limit 5 but not 5


// zcard counts the number of elements

$ redis-> zcard (‘zset1 ′); // 4


// zscore query element index

$ redis-> zscore (‘zset1 ′,’ ef ’); // 3


// zremrangebyscore deletes the elements of an index range

$ redis-> zremrangebyscore (‘zset1’, 0,2); // Delete the element with index between 0-2 (‘ab’, 'cd ’), return the number of deleted elements 2


// zrank / zrevrank returns the position of the table order / descending order of the elements (not the index)

$ redis-> zrank (‘zset1’, ’ef’); // Return 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’, 0,10); // Delete the element at position 0-10, return the number of deleted elements 2


/ **

Hash table operation

* /


// hset / hget access the data of the hash table

$ redis-> hset (‘hash1 ′,’ key1 ′, ’v1 ′); // Save the element whose key is‘ key1 ′ value is ‘v1’ into the hash1 table

$ redis-> hset (‘hash1 ′,’ key2 ′, ’v2 ′);

$ redis-> hget (‘hash1 ′,’ key1 ′); // Retrieve the value of key ‘key1’ in the table’hash1 ′ and return ‘v1 ′


// hexists returns whether the specified key in the hash table exists

$ redis-> hexists (‘hash1 ′,’ key1 ′); // true or false


// hdel deletes 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 it cannot be repeated

$ 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 ′)); // Return the corresponding value array (‘ v3 ′, ’v4 ′)


// hincrby accumulates the specified key

$ redis-> hincrby (‘hash1 ′,’ key5 ′, 3); // Return 3

$ 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 ′); // 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’); // Return array (2,3,17)

// Using parameters, you can use array (‘sort’ => ‘desc’, 'limit ’=> array (1, 2))

$ redis-> sort (‘tab’, array (‘sort’ => ‘desc’)); // Sort in descending order, return array (17,3,2)

$ redis-> sort ('tab', array ('limit' => array (1, 2))); // Return 2 elements in sequence position 1 (here 2 refers to the number, not the position) , Returns array (3,17)

$ redis-> sort ('tab', array ('limit' => array ('alpha' => true))); // Sort by first character returns array (17,2,3), because the first character of 17 It's '1' so the top position

$ redis-> sort (‘tab’, array (‘limit’ => array (‘store’ => ‘ordered’))); // indicates permanent sorting, returns the number of elements

$ redis-> sort ('tab', array ('limit' => array ('get' => 'pre_ *'))); // The wildcard character '*' is used to filter elements, which means that only the "pre_" is returned Element at the beginning


/ **

Redis management operations

* /


// select Specify the database to be operated

$ redis-> select (‘mydb’); // Specify as mydb, create if it does not exist


// flushdb clears the current library

$ redis-> flushdb ();


// move move the elements of the current library to other libraries

$ redis-> set (‘foo’, ‘bar’);

$ redis-> move (‘foo’, ‘mydb2’); // If ‘mydb2’ is in stock


// info display service status information

$ redis-> info ();


// slaveof configure slave server

$ redis-> slaveof (’127.0.0.1 ′, 80); // Configure the port 80 server of 127.0.0.1 as the slave server

$ redis-> slaveof (); // Clear slave server


// Synchronize saving server data to disk

$ redis-> save ();

// Asynchronously save server data to disk

$ redis-> bgsave ();

// ??

$ redis-> bgrewriteaof ();

// Return the time when the disk was last 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 the value corresponding to multiple keys

$ retval = $ redis-> mget (array_keys ($ mkv)); // Get 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 operation


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 KeyPrefixPreprocess or (‘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’,

),

);


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 key distribution strategy

$ 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']

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.