Introduction to Redis -- five data types and usage scenarios

redis Xiaobai beginner level

Install redis

See the installation tutorial here

Simple use

  1. Installing predis/predis through Composer

    composer require predis/predis

  2. Configure connection information
    The redis configuration file is: config/database.php

    'redis' => [
         'client' => 'predis',
         'default' => [
             'host' => env('REDIS_HOST', ''),
             'password' => env('REDIS_PASSWORD',null),
             'port' => env('REDIS_PORT', 6379),
             'database' => 0,
  3. test
    1. Create route > route:: get ('testredis'‘ RedisController@testRedis ’)->name(‘testRedis’);
    2. Create a controller with artist command > PHP artist make: controller rediscontroller
    3. Preparation

    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Models\Member;
    use Illuminate\Support\Facades\Redis;
    class RedisController extends Controller
     public function testRedis()
         Redis::set('name', 'guwenjie');
         $values = Redis::get('name');
         //Output: "guwenjie"
         //Add a small example. For example, a person or a news item on the homepage of the website has a high daily traffic, which can be stored in redis to reduce memory pressure
         $userinfo = Member::find(1200);
             $values = Redis::get('user_key');
             $values = Member::find(1200);//Here, you can change id=1200 to another ID for testing

Introduction to redis data types and application scenarios

1. String

As like as two peas, string is the most basic type of redis. You can understand it as a type that is exactly the same as Memcached, and a key corresponds to a value.
String types are binary safe. This means that the redis string can contain any data. For example, jpg images or serialized objects.
String type is the most basic data type of Redis. The value of string type can store 512MB at most.
Application scenario: String is the most commonly used data type. Ordinary key/ value storage can be classified as this type, that is, the current Memcached function can be fully realized and the efficiency is higher. You can also enjoy Redis's functions such as timing persistence, operation log and Replication. In addition to providing the same get, set, incr, decr and other operations as Memcached, Redis also provides the following operations:
-Get string length
-Add content to string append
-Sets and gets a section of the string
-Set and get a bit of the string
-Batch setting the contents of a series of strings

Usage scenario: general key value Caching Application. General count: number of microblogs and fans.
Implementation method: String is stored in redis. By default, it is a String referenced by redisObject. When encountering incr,decr and other operations, it will be converted to numerical type for calculation. At this time, the encoding field of redisObject is int

2. Hash

Redis hash is a collection of key value (key = > value) pairs.
Redis hash is a mapping table of field and value of string type. Hash is especially suitable for storing objects
Common commands: hget,hset,hgetall, etc.
Redis's Hash is actually a HashMap with internally stored values, and provides an interface to directly access the Map members

Note that Redis provides an interface (hgetall) that can directly get all attribute data. However, if there are many members of the internal Map, it involves the operation of traversing the entire internal Map. Due to Redis's single thread model, this traversal operation may be time-consuming, and the requests of other clients do not respond at all. This needs special attention.
Usage scenario: store some changed data, such as user information.
Implementation method: as mentioned above, the Value corresponding to Redis Hash is actually a HashMap. In fact, there are two different implementations. When the members of this Hash are relatively small, Redis will use a compact storage method similar to one-dimensional array instead of a real HashMap structure. The encoding of the corresponding value redisObject is zipmap, When the number of members increases, it will be automatically converted to a real HashMap. At this time, encoding is ht.


The list is a simple list of strings, sorted in insertion order. You can add an element to the head (left) or tail (right) of the list
Common commands: lpush (add the left element), rpush,lpop (remove the first element on the left), rpop,lrange (get list fragment, LRANGE key start stop), etc
Application scenarios: Redis list has many application scenarios, and it is also one of the most important data structures in Redis. For example, twitter's attention list and fan list can be realized by Redis's list structure.
List is a linked list. I believe anyone with a little knowledge of data structure should be able to understand its structure. Using the list structure, we can easily implement the latest message ranking and other functions. Another application of list is message queue,
You can use the PUSH operation of the List to store the task in the List, and then the worker thread takes out the task for execution with POP operation. Redis also provides an api to operate a section in the List. You can query directly and delete the elements of a section in the List.
Implementation method: Redis list is implemented as a two-way linked list, that is, it can support reverse lookup and traversal, which is more convenient for operation, but it brings some additional memory overhead. Many implementations within Redis, including sending buffer queue, also use this data structure.
Redis's list is a two-way linked list with each sub element of String type. You can add or delete elements from the head or tail of the list through push and pop operations. In this way, the list can be used as a stack or a queue. Getting elements closer to both ends is faster, but it is slower to access through the index.
Usage scenario: Message Queuing System: use list to build a queue system, and use sorted set to even build a priority queue system. For example, using Redis as a log collector is actually a queue. Multiple endpoints write log information to Redis, and then one worker writes all logs to disk.
Operation of getting the latest N data: record the list of the first N newly logged in user IDs, and the out of range can be obtained from the database

4.set ordered set

Set is an unordered set of type string. Set is realized through hashtable. The concept is basically similar to that of a set in mathematics. It can be intersection, union, difference set, etc. the elements in set are not in order. Therefore, the complexity of adding, deleting and searching is O(1)
Common commands: sadd,spop,smembers,sunion, etc.
Application scenario: Redis set's external functions are similar to those of a list. The special feature is that set can automatically eliminate duplication. When you need to store a list data and do not want duplicate data, set is a good choice, and set provides an important interface to judge whether a member is in a set set, This is also not provided by the list.
A Set is a Set. The concept of a Set is a combination of non repeating values. Using the Set data structure provided by Redis, you can store some collective data.
Case: in microblog, you can save all the followers of a user in one set and all their fans in one set. Redis also provides intersection, union, difference and other operations for collections, which can easily realize functions such as common concern, common preference, second degree friend and so on. For all the above collection operations, you can also use different commands to choose whether to return the results to the client or save them to a new collection.
Implementation method: the internal implementation of set is a HashMap whose value is always null. In fact, it can quickly eliminate duplication by calculating hash, which is why set can judge whether a member is in the set

5.zset unordered set

Like set, zset is also a collection of string elements, and duplicate members are not allowed
Common commands: zadd,zrange,zrem,zcard, etc
Usage scenario: the usage scenario of Redis sorted set is similar to that of set, except that set is not automatically ordered, while sorted set can sort members by providing an additional priority (score) parameter, and it is inserted orderly, that is, automatic sorting. When you need an ordered and non repetitive collection list, you can choose the sorted set data structure. For example, twitter's public timeline can be stored with the publication time as a score, so that it is automatically sorted according to time when it is obtained. Compared with set, sorted set is associated with a double weight parameter score, so that the elements in the set can be arranged orderly according to score. Redis sorts the members in the set from small to large through scores. The members of zset are unique, but the score can be repeated. For example, for a sorted set that stores the scores of the whole class, the set value can be the student number of the students, and the score can be the test score. In this way, the natural sorting has been carried out when the data is inserted into the set. In addition, the sorted set can also be used as a weighted queue. For example, the score of ordinary messages is 1 and the score of important messages is 2. Then the worker thread can choose to obtain work tasks in the reverse order of score. Give priority to important tasks.
Implementation method: within Redis sorted set, HashMap and skip list are used to ensure the storage and order of data. In HashMap, the mapping from member to score is stored, while in the skip table, all members are stored. The sorting is based on the score stored in HashMap. Using the structure of skip table can obtain relatively high search efficiency and simple implementation.

Basic methods of operating Redis with PHP

1. Simple operation of redis strng (string):

      //Set a string
       $value = Redis::get('name');
       var_dump($value);   //hello
       //Repeat set
       $value1 = Redis::get('name');
       var_dump($value1);   //world

2. Simple operation of redis list

  public function RedisList()
      //Add element on the left
      Redis::del('list');          //Empty table
      $value = Redis::lrange('list',0,-1); //Get all values
      var_dump($value);  //["book3","book2","book1"]
      //Add element from right
      $value = Redis::lrange('list',0,-1); //Get all values
      var_dump($value);  //["book3","book2","book1","book4"]
      $value = Redis::lrange('list',0,-1);  //["book2","book1","book4"]
      $value = Redis::lrange('list',0,-1);  //["book2","book1"]
      return $value;

3. Simple operation of redis hash

public function RedisHash()
      Redis::del('hash');          //Empty table
      //Set value for a key in hash table
      ////If not, the setting succeeds and returns 1. If it exists, it will replace the original value and return 0. If it fails, it will return 0
      //Get the value of a key in the hash
      $value = Redis::hget('hash','book'); //book1
     //Get all the values in the hash. All the values in the hash are random
      $arr = Redis::hvals('hash'); // ["book1","dog","banna","apple"]
      //Get all key s in hash
      $arr = Redis::hkeys('hash'); //["book","dog","banaa","apple"]
      //Get all the key values in the hash
      $arr = Redis::hgetall('hash');
      //Get the number of key s in the hash
      $key = Redis::hlen('hash');
      //Delete a key. If the table does not exist or the key does not exist, false is returned
      $del = Redis::hdel('hash','dog');
      $arr = Redis::hgetall('hash');
      return $arr;

4. Simple operation of redis set

public function RedisSet($value='')

       Redis::del('set');          //Empty table
       // Add element
       Redis::sadd('set', 'book');  //Repeated addition returns 0
       // View all elements in the collection
       $set = Redis::smembers('set');
       //Delete elements in the collection
       Redis::srem('set', 'book');
       //Determine whether the element is in the collection
       Redis::sismember('set','apple');  //Return true / false
       //View the number of collection members
       //Remove an element from the collection
       //Redis::spop('set');  // Returns the removed element

       //Returns the intersection of sets
       //Returns the intersection of sets and coexists in a new set
       // Collection merge

5. Simple operation of redis sorted set

public function RedisZset($value='')
      // code...
      Redis::del('zset');          //Empty table
      // Add element
      Redis::zadd('zset',1, 'book');  //Repeated addition returns 0

      // View all elements in the collection
      $zset = Redis::zrange('zset',0,-1);
      //Returns the score of the element
      $score = Redis::zscore('zset','dog');
      //Delete elements in the collection
      Redis::zrem('zset', 'book');
      //Returns the number of values between min and max in the collection
      //Returns a value in an ordered set whose score is between min and max
      $arr = Redis::zrangebyscore('zset',3,5);
      return $arr;

More references:

Tags: Laravel

Posted on Mon, 27 Sep 2021 21:03:43 -0400 by wrequed