PHP + Redis Basic operations

Source: Internet
Author: User
This article mainly introduces the PHP + Redis basic operation, has a certain reference value, now share to everyone, the need for friends can refer to

String type operation

The string is the most basic type of Redis, and the string type is binary safe. This means that a Redis string can contain any data. For example, JPG images or serialized objects

$redis->set (' key ', ' TK '); $redis->set (' number ', ' 1 '); $redis->setex (' key ', 5, ' TK '); Set a key value of 5 seconds (' key ', $redis->psetex, ' TK '). Set the key value $redis->setnx (' key ', ' XK ') with a validity period of 5000 milliseconds (same as 5 seconds); Returns False if the key value exists true$redis->delete (' key '); Delete key values can be passed in array (' Key1 ', ' Key2 ') to delete multiple keys $redis->getset (' key ', ' XK '); Set the value of key key to XK and return the original value of this key value tk $ret = $redis->multi ()//Bulk transaction, does not guarantee the atomicity of processing data->set (' Key1 ', ' val1 ')   Get (' Key1 ')->setnx (' key ', ' Val2 ')->get (' Key2 ')->exec (); $redis->watch (' key ');       Monitor if key key is modified by other client if key is modified between call watch () and EXEC (), Exec fail function f ($redis, $chan, $msg) {//channel subscription                    Switch ($chan) {case ' chan-1 ': Echo $msg;                Break                    Case ' chan-2 ': Echo $msg;                Break                    Case ' chan-2 ': Echo $msg;    Break }} $redis->subscribe (Array (' chan-1 ', ' chan-2 ', ' chan-3 '), ' F '); Subscribe to 3 chans$redis->publish (' chan-1 ', ' Hello, world! '); Send message. $redis->exists (' key '); Verify that the key exists and that there is a return true$redis->incr (' number '); Key value plus 1$redis->incrby (' number ',-10); Key value plus minus 10$redis->incrbyfloat (' number ', +/-1.5); $REDIS->DECR (' number ') of key value plus decrease. Key value minus 1$redis->decrby (' number ', 10); Key value minus 10$mget = $redis->mget (Array (' number ', ' key ')); Gets the key value in bulk, returns an array of $redis->mset (' key0 ' = ' value0 ', ' key1 ' = ' value1 '));                                         Bulk Set key value $redis->msetnx (Array (' key0 ' = ' value0 ', ' key1 ' = ' value1 ')); Bulk set the key value, similar to the SETNX () method bulk Operation $redis->append (' key ', '-smudge '); The original key value TK, appends the value to the key value, the key value is Tk-smudge$redis->getrange (' key ', 0, 5); Key value interception starts from 0 position to 5 position end $redis->getrange (' key ',-6,-1);                                     The string intercept starts from 6 (the penultimate 6th position) to 1 (the bottom 1th position) End $redis->setrange (' key ', 0, ' Smudge '); The replacement string in the key value, 0 indicates how many characters are replaced at the beginning of the 0 position, where the kanji occupies 2 positions $redis->strlen (' key '); Key value lengthEdis->getbit (' key '); $redis->setbit (' key '); 

List Linked list operations

$redis->delete (' List-key '); Delete Linked list $redis->lpush (' List-key ', ' A '); Insert list Header/left, return list length $redis->rpush (' List-key ', ' B ');                  Insert the tail/right of the linked list, return the list length $redis->lpushx (' List-key ', ' C ');                  Insert list header/left, linked list does not exist return 0, the presence is inserted successfully, returns the current list length $redis->rpushx (' List-key ', ' C '); Insert list end/Right, linked list does not exist return 0, the presence is inserted successfully, return the current list length $redis->lpop (' List-key '); Returns the value at the top (left) of the list, followed by first out (stack) $redis->rpop (' List-key ');                     Returns the value of the list tail (right), first-in, first-out (queue) $redis->blpop (), $redis->brpop (), $redis->lsize (' List-key '); If the list returns the list length, the empty list returns 0 if it is not a linked list or is not empty, then returns false to determine the non-linked list "= = = False" $redis->lget (' List-key ',-1); Get the list element by index 0 Gets the left one-1 gets the last $redis->lset (' List-key ', 0, ' X ');                     0 position elements replaced by X$redis->lrange (' List-key ', 0, 3); List interception from 0 start 3 position end, end position is-1 get all $redis->ltrim after start position (' List-key ', 0, 1); Intercept list (irreversible) starting from 0 Index 1 index end $redis->lrem (' List-key ', ' C ', 2);       The linked list removes elements from the left 2 C$redis->linsert (' List-key ', Redis::before, ' C ', ' X ');              Insert x in front of the C element, Redis::after (indicates a later insert) if the list does not exist then insert failure returns 0 if the element does not exist return -1$redis->rpoplpush (' L                     Ist-key ', ' List-key2 '); POPs an element from the source list and presses the element from the top of the target list (to the left) into the target list.                    $redis->brpoplpush (); Rpoplpush blocking version, this version has a third parameter to set the blocking time that is, if the source list is empty, you can block the time to listen for timeout, and if there are elements, perform the operation.

Set Collection type

Set unordered collection does not allow duplicate element server to implement multiple collection operations $redis->smembers (' key ');                 Gets the container key in all elements $redis->sadd (' key ', ' TK '); (insert from left, last inserted element at 0 position), TK is already present in the collection, return false does not exist add successful return True$redis->srem (' key ', ' TK '); Remove the Tk$redis->smove (' key ', ' key1 ', ' TK ') in the container; Moving the element TK in the easy key to the container Key1 operation successfully returns True$redis->sismember (' key ', ' TK '); Checks if value is a member of the Set container $redis->scard (' key '); Returns the number of members of the Set container $redis->spop (' key ');      Randomly returns an element in the container and removes the element $redis->srandmember (' key ');//randomly returns an element in the container without removing the element $redis->sinter (' key ', ' key1 '); Returns the intersection of two sets no intersection returns an empty array, and if the argument has only one set, returns the complete array of $redis->sinterstore (' Store ', ' key ', ' Key1 ') corresponding to the set; The intersection of the collection key and the collection Key1 in the Container store successfully returns 1$redis->sunion (' key ', ' key1 ');             Collection key and set Key1 Note that even if multiple collections have the same element, only one $redis->sunionstore (' Store ', ' key ', ' Key1 ') is retained; Collection key and collection Key1 are saved in the collection store, note that even if multiple collections have the same element, only one $redis->sdiff (' key ', ' key1 ', ' Key2 ') is retained; Returns an array of elements that exist in the key collection and do not exist in the collection Key1 Key2

zset Data Types

* * (stored set) is a collection of strings, unlike set, where each element is associated with a double-type Scoreredis list type, which is actually a doubly linked list in which each child element is a string type.                            * * $redis->zadd (' TKey ', 1, ' A '); Insert Collection TKey, a element associated with a fraction, insert successfully returns 1 at the same time the collection element cannot be duplicated, if the element already exists return 0$redis->zrange (' TKey ', 0,-1);                     Gets the collection element, from 0 positions to 1 bits $redis->zrange (' TKey ', 0,-1, true); Gets the collection element, from 0 positions to 1 positions, returns an associative array with a fractional array ([A] = 0.01,[b] = 0.02,[d] and 0.03) where the decimal is from the Zadd party The second parameter of $redis->zdelete (' TKey ', ' B '); Removal of element B in the collection TKey successfully returned 1 failed to return 0$redis->zrevrange (' TKey ', 0,-1);                 Gets the collection element, from 0 positions to 1 bits, the array is processed in descending order of score $redis->zrevrange (' TKey ', 0, -1,true); Gets the collection element, from 0 positions to 1 bits, the array is processed in descending order of score to return score associative array $redis->zrangebyscore (' TKey ', 0, 0.2,array (' withscores ' = True))             ; Get a few TKey in score in the interval [0,0.2] element, score from low to high ordering, elements with the same score, then sorted in dictionary order, Withscores control returns associative array $redis->zrangeb Yscore (' TKey ', 0.1, 0.36, Array (' withscores ' = TRUE, ' LimiT ' = = Array (0, 1)); where limit 0 and 1 are taken to match the condition set starting from 0 position, backward Scan 1 return associative array $redis->zcount (' TKey ', 2, 10); Gets the number of TKey score in the interval [2, 10] elements $redis->zremrangebyscore (' TKey ', 1, 3);                          Remove the element $redis->zremrangebyrank (' TKey ', 0, 1) in TKey score in the interval [1, 3] (with the boundary);  The default element score is incremented, removing elements from the TKey from 0 to 1 position end $redis->zsize (' TKey '); Returns the number of elements stored in an ordered set of keys $redis->zscore (' TKey ', ' A ');                       Returns the score value of element A in the collection TKey $redis->zrank (' TKey ', ' a '); Returns the index value of element A in the collection TKey the elements in the Z collection are arranged from low to high in the score, that is, the lowest score index is 0$redis->zincrby (' TKey ', 2.5, ' A ' );         Adds the score value of element A in the collection TKey to 2.5$redis->zunion (' Union ', Array (' TKey ', ' tkey1 ')); Merges the collection TKey and collection tkey1 elements into the collection union, and the elements in the new collection cannot repeat the number of elements of the new collection, and if element A is present in both TKey and Tkey1, then the score of the merged element A is added $redis->zunion (         ' Ko2 ', Array (' K1 ', ' K2 '), Array (5, 2)); The collection K1 and collection K2 are set in K02, and the number of elements in array (5,1) corresponds to the subcollections, and then 5 corresponds to K1 k1 Each element score is multiplied by 5, 1 corresponds to K2,K2 per element score multiplied by 1 and then the element follows Increment sort, default the same element sThe core (SUM) is added $redis->zunion (' Ko2 ', Array (' K1 ', ' K2 '), Array (2), ' MAX ');         After each subset is multiplied by a factor, the elements are sorted incrementally, and the score of the same element (max) can also be set min to take the minimum value $redis->zinter (' Ko1 ', Array (' K1 ', ' K2 ')); The collection K1 and collection K2 intersect at K01, and are incremented by the score value if the collection element is the same, the score value of the elements in the new collection is added $redis->zinter (' Ko1 ', Array (' K1 ', ' K2 '), Array (5         , 1)); The collection K1 and collection K2 intersect at K01, and the number of elements in array (5,1) corresponds to the subcollections, and then 5 corresponds to K1 k1 Each element score is multiplied by 5, 1 corresponds to K2,K2 per element score multiplied by 1, then the element SCO         Re in ascending order, by default the same element score (SUM) Add $redis->zinter (' Ko1 ', Array (' K1 ', ' K2 '), Array (5, 1), ' MAX '); After each subset is multiplied by a factor, the element score in ascending order, and the same element score the maximum (max) can also set min to take the minimum value

Hash data type

Redis Hash is a string-type field and value mapping table. It is added, and the delete operation is O (1) (average). Hash is ideal for storing objects. $redis->hset (' h ', ' name ', ' TK ');         Add the Name field in the H table value to Tk$redis->hsetnx (' h ', ' name ', ' TK '); Add the Name field in the H table value for TK if the field name value exists return false otherwise return True$redis->hget (' h ', ' name '); Get the Name field Value$redis->hlen (' H ') in the H table; Gets the H table length that is the number of fields $redis->hdel (' h ', ' email '); Delete the e-mail field $redis->hkeys (' H ') in the H table; Get all fields in H table $redis->hvals (' H '); Get all fields in H table Value$redis->hgetall (' H '); Gets all fields in the H table and value returns an associative array (character Chewei value) $redis->hexists (' h ', ' email ');  Determine if the e-mail field exists with the table H does not exist return False$redis->hset (' h ', ' age ', +); $redis->hincrby (' h ', ' age ',-2);          Set the Age field in h table Value Plus (-2) if value is a non-numeric value then return False otherwise, return the operation after the Value$redis->hincrbyfloat (' H ', ' age ',-0.33); Set the Age field in the H table value Plus (-2.6) if value is a non-numeric value returns false otherwise returns the value after the operation (the decimal point retains 15 bits) $redis->hmset (' h ', Array (' Score ' =&gt ; ' Salary ', ' + 2000 '); Table H Batch setup fields and Value$redis->hmget (' H ', Array (' score ', ' salary ')); Table h The value of the bulk fetch field

Related recommendations:

Php+redis Implementing session Sharing

A simple example of php+redis sharing

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.