Introduction to middleware Redis

Redis overview

what is redis

Redis is a cache database that supports multiple data structures such as key-value , written in C language

  • Can be used in scenarios such as caching, event publishing and subscription, high-speed queues, etc.
  • Provide direct access to strings, hashes, lists, queues, collections ,
  • Based on memory , can be persistent

Why use redis

  • Very fast reading and writing
    • The reading speed is 110,000 times per second, and the writing speed is 80,000 times per second
  • Supports multiple data types
    • Support Strings, Lists, Hashes, Sets and Ordered Sets data type operations in binary cases
  • atomicity
    • All redis operations are atomic, and redis also supports atomic execution of several operations
  • Persistence
    • Support RDB, AOF and other persistence methods
  • Support publish-subscribe mode
  • Support distributed services

Redis is single-threaded, and Redis is based on memory operations.

So the performance bottleneck of Redis is not CPU, but machine memory and network bandwidth.

So why is Redis so fast and has such high performance? QPS reaches 10W+

Why is Redis single-threaded so fast?

  • Myth 1: A high-performance server must be multi-threaded?
  • Myth 2: Multi-threading (CPU context switching!) must be more efficient than single-threading!

Core: Redis puts all data in memory, so it is the most efficient to use a single thread to operate, multi-threaded (CPU context will switch: time-consuming operation!), for the memory system, if there is no context Switching efficiency is the highest. Multiple reads and writes are performed on one CPU. In the case of storing data in memory, single thread is the best solution.

Redis usage scenarios

Summary of redis application scenarios Redis is usually used in a lot of places. The following is a summary of the application scenarios we understand:

¶Cache of hotspot data

Caching is the most common application scenario of Redis. The reason why it is used in this way is mainly because of the excellent read and write performance of Redis. And it gradually replaces memcached and becomes the preferred server-side cache component. Moreover, Redis supports transactions internally, which can effectively ensure data consistency when used.

When used as a cache, there are generally two ways to save data:

  • Before reading, read Redis first. If there is no data, read the database and pull the data into Redis.
  • When inserting data, write to Redis at the same time.

Option 1: It is simple to implement, but there are two points to note:

  • Avoid cache breakdown. (The data that needs to be hit if the database does not have it, causing Redis to have no data and always hit the database.)
  • The real-time performance of the data is relatively poor.

Solution 2: The real-time data is strong, but it is not convenient for unified processing during development.

Of course, the two methods are applicable according to the actual situation. For example: Option 1 is suitable for scenarios that do not have particularly high requirements for real-time data. Solution 2 is suitable for dictionary tables and data storage with a small amount of data.

¶Application of time-limited business

In redis, you can use the expire command to set the lifetime of a key, and redis will delete it after the time expires. This feature can be used in business scenarios such as time-limited promotional information and mobile phone verification codes.

¶Counter related issues

Because the incrby command can achieve atomic increment, redis can be used in high-concurrency spike activities and the generation of distributed serial numbers. The specific business is also reflected in such as limiting the number of text messages sent by a mobile phone number, and how many requests are limited by an interface in one minute. , How many times an interface can be called a day, etc.

¶Distributed lock

This is mainly done using the setnx command of redis. setnx: "set if not exists" means that if it does not exist, the cache is successfully set and returns 1, otherwise it returns 0. This feature is used in the background of Yu Youbenyuan, because our server It is a cluster, and the scheduled task may run on both machines, so in the scheduled task, first set a lock through setnx, and execute it if it is set successfully. If it is not successfully set, it indicates that the scheduled task has been executed. Of course, in combination with specific businesses, we can add an expiration time to this lock. For example, if a scheduled task is executed once every 30 minutes, then the expiration time can be set to a time less than 30 minutes. This is related to the cycle of the scheduled task and the execution of the scheduled task. time-consuming.

In the scenario of distributed locks, it is mainly used in seckill systems, for example.

¶Delayed operation

For example, after the order is produced, we occupy the inventory. After 10 minutes, we will check whether the user has actually purchased it. If there is no purchase, the document will be invalidated and the inventory will be restored at the same time. Since redis provides the Keyspace Notifications function since version 2.8.0, it allows customers to subscribe to Pub/Sub channels in order to receive events affecting Redis datasets in a certain way. So we can use the following solution for the above requirements. We set a key when the order is produced, and set it to expire after 10 minutes. We implement a listener in the background to monitor the actual effect of the key. logical plus.

Of course, we can also use the delay queue service of message middleware such as rabbitmq and activemq to realize this requirement.

¶Leaderboard related issues

The query speed of relational databases is generally slow in terms of leaderboards, so you can use redis's SortedSet to sort hot data.

For example, create a SortedSet for the like list, then use the user’s openid as the above username, use the user’s likes as the above score, and then make a hash for each user, and use zrangebyscore to get the ranking according to the number of likes list, and then obtain the user's hash information according to the username, which was quite good in actual use.

¶Storage of mutual relationships such as likes and friends

Redis uses some commands of sets, such as intersection, union, difference, etc.

In the Weibo application, the people that each user follows are stored in a collection, so it is easy to realize the function of seeking mutual friends of two people.

Simple Queue

Since Redis has commands such as list push and list pop, it is very convenient to perform queue operations.


Redis basic operation commands

start up

  1. The default installation directory of the startup command: usr/local/bin(/usr is a very important directory, similar to Program Files under Windows, which stores user programs)

  2. redis.conf configuration file

    • daemonize: daemon mode, control whether the background is started by default
      • yes-start: In this mode, redis will run in the background and write the process pid number to the file set by the redis.conf option pidfile. At this time, redis will always run unless the process is manually killed.
      • no-off: When the daemonize option is set to no, the current interface will enter the command line interface of redis, and the forced exit of exit or the closing of connection tools (putty, xshell, etc.) will cause the redis process to exit.
  3. Start the redis service by making a configuration file

    • redis-server hconfig/myredis.conf 
      
  4. Check whether the redis server process is enabled

    • ps -ef|grep redis
      

      [External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-oQ8GqGGa-1651558279836)(Redis.assets/image-20220105134017082.png)]

  5. Use the port number test specified by redis-cli connection, the default port of redis is 6379 (Add the parameter --raw, you can force the output of Chinese, otherwise it will be garbled

    • redis-cli -p 6379
      

Guess you like

Origin blog.csdn.net/qq_50596778/article/details/124554671