PHP using Redis instance to explain

Source: Internet
Author: User
Tags set set


Redis is an open source API that is written in ANSI C, supports the web, can be persisted in memory, key-value databases, and provides multiple languages. Redis supports data types such as String (string), list, Hash (dictionary), set (set), Sorted set (ordered set); Redis default Port 6379.

1. Connect

$redis = new Redis ();  Instantiation of $redis->connect (' 127.0.0.1 ', 6379);  Connect $redis->auth (' redis password ');   Redis with no password can ignore this step

2. Data type

2-1 string Strings

Store or change $redis->set (' Test ', ' AAA ');//Get Value $redis->get (' Test ');   Aaa

2-2 List

The L in the method represents the list operation
  1. Store

    $redis->lpush (' list ', ' a ');    Add $redis->lpush (' list ', ' B ') from the left, $redis->lpush (' list ', ' C ');        $redis->rpush (' list ', ' d ');    Add $redis->lset (' list ', 2, ' e ') from the right,///To set or change the value of the specified position in the list, return 1 successfully, fail to return error message
  2. Delete

    $redis->lpop (' list ');      Delete the first $redis->rpop (' list ') on the left.      Delete Right First//$redis->lrem (' list name ', ' value ', num); Delete the element according to the value, the second parameter is the value to be deleted (the value of the element to be deleted),//The third parameter num means: from where to delete, delete a few,//num>0 from the table head to the end of the deletion    , deleted num ends;    //num<0 Delete |num| from the end of the table to the header    //num=0 Remove all elements in the table that have values of ' B '    $redis->lrem (' list ', ' B ', 2);
  3. Gets, returns an array

    $redis->lrange (' list ', 0,-1);  Returns an array. The element of the specified range in the list stored in key,/     /The first parameter is the list name    //The second parameter is the starting bit subscript,    //The third is the end bit subscript (contains the end bit element).    //Negative number is the reciprocal,-1 is the countdown first;    //If the start is greater than the end return null, the end is greater than the actual length, returning to the last element. $redis->lgetrange (' list ', 0, 2);//Gets the value of the specified interval of the list, as above $redis->ltrim (' list ', 0, 3);   Intercepts and retains the value of the specified interval for the list, and the remaining values are deleted.    //Successfully returned 1, failed to return error message. Negative numbers represent the reciprocal $redis->lsize (' list ');         Gets the length of the list $redis->lget (' list ', 2)        //Gets the value of the list at the specified position $redis->lindex (' list ', 2);     Gets the value of the specified position in the list

2-3 Hash Dictionary

A string type of field and value mapping table, especially suitable for storing objects. Each hash can store 2 of 32 square-1 key-value pairs (more than 4 billion) the hash table is equivalent to the key in Redis storage key = value  and the table content equals the value method h for the hash operation
  1. Store

    //$redis->hset (' hash table ', key, value); If the hash table does not exist, create a hash table, if the key is not present, set success, return True,//if present, replace the original value, return FALSE, return false///The first argument is the dictionary name $redis->hset ('   Hashtest ', ' a ', ' AAA ');  Returns True $redis->hset (' hashtest ', ' A ', ' BBB ');  The value of the returned False,a is changed to BBB $redis->hset (' hashtest ', ' B ', ' BBB ');   Returns true, increasing B, with a value of Bb$redis->hmset (' Hashtest ', [1 = 1, 2 = 2, 3 = 3]);   Bulk assignment, $redis->hincrby (' hashtest ', ' 1 ', 1); The value of the key corresponding to the hash table is increased by 1 (integer),/////The first parameter dictionary name//The second parameter is the key name,//The third parameter is the amplitude of self increment.        If the key does not exist in the table, the key is added automatically and the value is set to self-increment $redis->hincrbyfloat (' hashtest ', ' 2 ', 1.5); The key in the hash table is self-increment 
  2. Get

    $redis->hget (' hash table ', key);        Get the value corresponding to a key    $redis->hget (' hashtest ', ' a '),//Get the value of a in Hashtest $redis->hkeys (' hashtest ');     Gets all keys (key names) in the hash table, returns an array   $redis->hvals (' hashtest '), and//gets all values in the hash table, ordered randomly, returning an array $redis-> Hgetall (' hashtest ');   Gets all the key-value pairs in the hash table, sequentially randomly, returning an array of $redis->hlen (' hashtest ');      Gets the number of keys in the hash table   $redis->hmget (' hashtest ', [1, 2, 3]);//Bulk get multiple keys corresponding to value, the second parameter is keyarr$redis->hexists (' Hashtest ', ' B ');      Determine if the key exists in the hash table
  3. Delete

    $redis->hdel (' hashtest ', ' a ');     Delete a key in the hash table, successfully returns TRUE,    //If the table does not exist or the key does not exist return false

2-4 Set Set

Redis's set is an unordered collection of type String. A collection member is unique, which means that duplicate data cannot appear in the collection. The maximum number of members in the collection is 2 of 32 square-1 (4294967295, each collection can store 40多亿个 members). The S in the method represent the set operation
  1. Add

    //$redis->sadd (' Set set ', ' value ');//Add a value to Settest, success, return the number of additions, Failed to return 0.  The first parameter is the Set collection name//The second parameter is the insertion of a new value into the collection, that is: inserting a new value into value $redis->sadd (' settest ', ' a ');  1 $redis->sadd (' settest ', ' B ');  1 $redis->sadd (' settest ', ' a ');  0$redis->sadd (' settest ', [' C ', ' d ', ' e ']); Add more than one value at a time 
  2. Get

    $redis->smembers (' settest ');   Gets all the elements in the collection $redis->sismember (' Settest ', ' B '); Determines whether the element is a set member $redis->scard (' Settest ');      View the number of elements in the collection $redis->sinter (' settest ', ' settest2 '); Returns the intersection of two sets of $redis->sinterstore (' Settest3 ', ' settest ', ' settest2 ');    Place the intersection of Settest and Settest2 in the collection Settest3 $redis->sunion (' settest ', ' settest2 '); Returns a collection of two sets of $redis->sunionstore (' Settest4 ', ' settest ', ' settest2 ');    The settest and Settest2 are placed in the set Settest4 $redis->sdiff (' settest ', ' settest2 ');  Returns the difference set of two sets $redis->sdiffstore (' Settest5 ', ' settest ', ' settest2 '); Place the difference between settest and Settest2 in the collection Settest5
  3. Delete

    $redis->srem (' settest ', ' a ');  Delete a value from the collection, $redis->srem (' settest ', ' A ', ' B '); Delete multiple values    $redis->spop (' settest ');       Removes a random element from the collection and returns the element

2-5. Sorted set ordered set

A Redis ordered collection is a collection of elements of type string, as well as a collection, and does not allow duplicate members. The difference is that each element is associated with a double-type fraction. Redis is a small-to-large ordering of the members in a collection by fractions. The members of an ordered collection are unique, but fractions (score) can be duplicated. The maximum number of members in the collection is 2 of 32 square-1 (4294967295, each collection can store 40多亿个 members). Z in method represents an ordered set operation
  1. Add or update

    $redis->zadd (' ordered set name ', fraction, value);   A value in Ztest to an ordered collection, which can be an integer value or a double-precision floating-point number. When Zadd is executed, a new ordered set is created if it does not exist, or an error is returned if ztest exists but is not an ordered set type.    $redis->zadd (' ztest ', 1, ' a ');     $redis->zadd (' Ztest ', 2, ' a ');         When an element is present, update the fraction of the element and reinsert the element to ensure that the element is in the correct position.        //But not the newly added $redis->zadd (' ztest ', score 1, value 1, score 2, value 2);   Inserting multiple values into an ordered set    $redis->zadd (' Ztest ', 2, ' B ', 3, ' C ', 4, ' d '); $redis->zincrby (' Set ', 2, ' C ');  Specified value c increased by 2
  2. Get

    $redis->zrange (' z set ', start bit, end bit, boolean value); Gets an ordered collection of specified intervals. Returns an array. Score from small to large. First parameter: Ordered set name//second parameter: Start position,//third parameter: End position (including the position), negative number is the last,//fourth parameter: Optional parameter, Boolean value, whether it has a score, default false    $redis->zrange ( ' Ztest ', 0, 1);     [' A ', ' B ']   sorted by fractions, but without fractions    $redis->zrange (' Ztest ', 0, 1, true);//[' A ' = 2, ' B ' + 2] sorted by fractions and carry fractions [' element ' = ' score '] $redis->zrevrange (' Zset ', 1, 2);   Gets an ordered collection of specified intervals. Returns an array. Score from big to small. $redis->zscore (' ztest ', ' a ');  Gets the fractional $redis->zcard (' Zset ') of the specified element;         Gets the number of stored elements $redis->zcount (' Zset ', 2, 5);  Number of elements with fractions between 2~5 $redis->zrangebyscore (' Zset ', 2, 3);   Returns the element with a fraction of a number of elements, without fractions, displayed in the same way as Zrange$redis->zrangebyscore (' Zset ', 2, 3, [' withscores ' = true]); Returns the element with a fraction of one or both, with a fractional display, displayed in the same way as Zrange
  3. Delete

    $redis->zrem (' Zset ', ' C ');     Deletes the specified member $redis->zremrangebyscore (' Set ', 2, 3);     Removes an element that has a score of between or below and returns the number of deletions

3. Other common methods

3-1 finding the relevant key

According to the conditions of the corresponding key (key), support string concatenation  (The return value is an array, even if the data is not found to return an empty array)     //* for any character arbitrary length,? Any character one length $redis->keys (' a ');  Find the key that equals a $redis->keys (' A * ');  Find the key that begins with a, followed by any value, $redis->keys (' *b* ');  Find the link middle contains B's key $redis->keys (' C?? ');   Find the key of length 3, and the first character is C $ A = A; $redis->keys ($a. ' * ');//Use the For Loop Plus get () to get the corresponding value for the keys after using the keys

3-2 Expiration Time

    1. View Expiration Time

      $redis->ttl (' Key Name ');        View the remaining time of a key's validity period and return the number of seconds.  //when no expiry time, return: 1;//When the key value is not returned-2;     $redis->ttl (' ttltest ');    View Ttltest remaining Expiration time
    2. Set Expiration Time

      Redis::expire (' key ', second);  How many seconds after expiration redis::expireat (' key ', timestemp);  Expires at a time stamp (seconds)

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.