The basic use case of Redis in PHP

Source: Internet
Author: User
Tags cas crc32

Download Http://www.oschina.net/p/redis

After decompression, there are: Lib source files, examples examples, test tests

Copy the Lib directory to your project and you can start your Predis operation.

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 IP, port, and corresponding database for the connection
$server = Array (
' Host ' = ' 127.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; Show ' Predis '

Setex Set a storage aging
$redis->setex (' str ', ten, ' Bar '); Indicates that the storage is valid for 10 seconds

Setnx/msetnx equivalent to an add operation that does not overwrite an existing value
$redis->setnx (' foo ', 12); True
$redis->setnx (' foo ', 34); False

Getset operation, set variant, result return value before replacement
$redis->getset (' foo ', 56);//Return 34

INCRBY/INCR/DECRBY/DECR increment and decrement of values
$redis->incr (' foo '); Foo is 57
$redis->incrby (' foo ', 2); Foo is 59

exists detect if a value exists
$redis->exists (' foo ');//true

Del Delete
$redis->del (' foo ');//true

Type detection, string returned by strings, List returns List,set table returns Set/zset,hash table returns hash
$redis->type (' foo ');//Not present, return none
$redis->set (' str ', ' test ');
$redis->type (' str '); String that returns a string

Append connecting to a string that already exists
$redis->append (' str ', ' _123′ '); Returns the cumulative string length of 8, which is ' test_123′ ' for the input str

SETRANGE Partial substitution operation
$redis->setrange (' str ', 0, ' abc '); Returns 3, Parameter 2 is 0 o'clock equivalent to set operation
$redis->setrange (' str ', 2, ' CD ');//returns 4, indicating a replacement from the 2nd word specifier, when ' str ' is ' ABCD '

SUBSTR Partial fetch operation
$redis->substr (' str ', 0,2);//= from No. 0, take 2nd character, total 3, return ' ABC '

Strlen Get string length
$redis->strlen (' str '); Returns 4

Setbit/getbit bit storage and acquisition
$redis->setbit (' binary ', 31, 1); 1 in the 31st place, there may be a size end problem? But it doesn't matter, getbit should be fine.
$redis->getbit (' binary ', 31); Returns 1

Keys Fuzzy Lookup function, support * number and number (match one character)
$redis->set (' foo1′,123);
$redis->set (' foo2′,456);
$redis->keys (' foo* '); Returns an array of foo1 and Foo2
$redis->keys (' F?o? '); Ditto

Randomkey randomly returns a key
$redis->randomkey (); may be to return ' foo1′ or ' foo2′ and any other key that exists in Redis

Rename/renamenx to rename the key, the difference is that Renamenx is not allowed to change to the existing key
$redis->rename (' str ', ' str2′ '); Changed the key named ' str ' to ' str2′

Expire set Key-value timeliness, TTL gets the remaining validity period, persist reset to permanent storage
$redis->expire (' foo ', 1); setting is valid for 1 seconds
$redis->ttl (' foo '); return validity value 1s
$redis->expire (' foo '); Cancel expire behavior

Dbsize returns the total number of records for the Redis current database
$redis->dbsize ();

/*
Queue operations
*/

Rpush/rpushx an ordered list operation, inserting elements from the queue
The difference between lpush/lpushx and rpush/rpushx is that it is inserted into the head of the queue, ditto, ' X ' means only the existing key is manipulated
$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 an existing queue, otherwise returns 0
Llen returns the current list length
$redis->llen (' foolist ');//3

Lrange returns an element of an interval in a 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 the No. 0 to the penultimate, which is equivalent to returning all elements, noting that many times in redis use negative numbers, the same

Lindex returns the list element for the specified order position
$redis->lindex (' foolist ', 1); Back to ' bar1′

LSet Modifying the value of a specified position in a 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 from 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 '); ' bar2′

LTrim queue modification, leaving several elements on the left, remaining deleted
$redis->ltrim (' foolist ', 0,1); Keep No. 0 to 1th elements from the left

Rpoplpush pop out elements from one queue and push 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 inserting elements before or after a specified element in the middle of a queue
$redis->linsert (' list2′, ' before ', ' ab1′, ' 123′ '); Represents the insertion of ' 123′ before the element ' ab1′ '
$redis->linsert (' list2′, ' after ', ' ab1′, ' 456′ '); Represents the insertion of ' 456′ ' after the element ' ab1′ '

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)
The Brpoplpush also blocks and waits for the operation, with the same result as Rpoplpush
$redis->blpop (' list3′,10); If List3 is empty, wait until the first element pops up when it is not empty and time out after 10 seconds

/**
Set table operation
*/

Sadd adds element, returns True, returns false repeatedly
$redis->sadd (' set1′, ' ab ');
$redis->sadd (' set1′, ' CD ');
$redis->sadd (' set1′, ' ef ');

Srem removing 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 returns the number of current set table elements
$redis->scard (' set2′);//2

Sismember determines whether an 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 a third table
$redis->set (' foo ', 0);
$redis->sinterstore (' foo ', ' set1′ '); This is equivalent to copy the ' set1′ ' content to ' foo ' and convert ' 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 returns a random element in a table
$redis->srandmember (' set1′);

/**
Ordered set table operation
*/

Sadd add element and set ordinal, return True, return false repeatedly
$redis->zadd (' zset1′,1, ' ab ');
$redis->zadd (' zset1′,2, ' CD ');
$redis->zadd (' zset1′,3, ' ef ');

Zincrby the index value of the specified element, changing the order of the elements
$redis->zincrby (' zset1′,10, ' ab ');//Return 11

Zrem removing the specified element
$redis->zrem (' zset1′, ' ef '); True or False

Zrange returns the elements of a specified interval in a table by position order
$redis->zrange (' zset1′,0,1); Returns the elements between positions 0 and 1 (two)
$redis->zrange (' zset1′,0,-1);//returns the element between position 0 and the penultimate element (equivalent to all elements)

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 returns the elements of the specified index interval in the table in order/descending
$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 the element between the index value 2-9 and contains the 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), indicating a maximum return of 2, with the result of an array (' EF ', 3), array (' GH ', 5))

Zunionstore/zinterstore to save the set/intersection of multiple tables in another table
$redis->zunionstore (' Zset3′,array (' zset1′, ' zset2′, ' zset0′ '); Will ' zset1′, ' zset2′, ' zset0′ ' and set in ' zset3′
Other parameters
$redis->zunionstore (' Zset3′,array (' zset1′, ' zset2′ '), array (' weights ' = = Array (5,0))), the//weights parameter represents weights, An element with a value greater than 5 that represents a set after the first, and a 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 3-5 but not 3, so it can be used similarly ' (5′ means 5 but not 5

Zcard Number of statistics elements
$redis->zcard (' zset1′);//4

Zscore 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 '), and return the number of deleted elements 2

Zrank/zrevrank returns the table order/descending position of the element (not an index)
$redis->zrank (' zset1′, ' ef ');//returns 0 because it is the first element; Zrevrank returns 1 (last)

Zremrangebyrank Delete an element of a specified position interval in a table
$redis->zremrangebyrank (' zset1′,0,10); Delete element with position 0-10, return number of deleted elements 2

/**
Hash table operation
*/

Hset/hget access to 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 whether the specified key exists in the hash table
$redis->hexists (' hash1′, ' key1′); True or False

Hdel Delete 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 accessing multiple elements into a 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 13

Hkeys returns all keys in the hash table
$redis->hkeys (' hash1′); Return Array (' key1′, ' key2′, ' key3′, ' key4′, ' key5′ ')

Hvals returns all the value 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 operations
*/

Sort sorts
$redis->rpush (' tab ', 3);
$redis->rpush (' tab ', 2);
$redis->rpush (' tab ', 17);
$redis->sort (' tab '); Returns an array (2,3,17)
Using parameters, you can combine arrays (' sort ' = ' desc ', ' limit ' = = = Array (1, 2))
$redis->sort (' tab ', Array (' sort ' = ' desc ')); Sort Descending, returning array (17,3,2)
$redis->sort (' tab ', Array (' limit ' = = = Array (1, 2))); Returns an array of 1 elements in the order position 2 (where 2 refers to the number, not the position), and returns a list (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 is ' 1′ so the first place
$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_* ')); A wildcard ' * ' filter element is used to return only elements that begin with ' pre_ '

/**
Redis Management Operations
*/

SELECT specifies the database to manipulate
$redis->select (' mydb '); Specified as MyDB, does not exist then creates

Flushdb emptying the current library
$redis->flushdb ();

Move moves the elements of the library into other libraries
$redis->set (' foo ', ' Bar ');
$redis->move (' foo ', ' mydb2′ '); If the ' mydb2′ stock is

Info Display service When status information
$redis->info ();

Slaveof configuration from the server
$redis->slaveof (' 127.0.0.1′,80); Configure the 127.0.0.1 port 80 server as the slave server
$redis->slaveof (); Clear from server

Save server data to disk synchronously
$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 key corresponding value
$retval = $redis->mget (Array_keys ($mkv)); Gets the value corresponding to multiple keys
Print_r ($retval);

Bulk operations
$replies = $redis->pipeline (function ($pipe) {
$pipe->ping ();
$pipe->flushdb ();
$pipe->incrby (' counter ', 10); Incremental operations
$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 ' and $zsetKey,//Key that needs to being 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* 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 (
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 Policies
$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[' db15 ' [' Keys ']

The basic use case of Redis in PHP

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.