Redis, the good partner of databases

Mondo Technology Updated on 2024-02-08

Redis is a key-value database that uses memory to store data, so it is often used in situations where data needs to be cached, which can relieve the pressure on many back-end databases. In this article, we'll briefly introduce what Redis provides and where it can be used.

The official website of Redis lists each of the supported commands, so let's take a look at the simplest one first

redis> set mykey "hello"redis> get mykey"hello"
As mentioned earlier, Redis is a database with a key-value structure, so the simplest set is to set the value of a key, and if you want to retrieve it, you can use get.

redis> set mykey "10"redis> decr mykey(integer) 9redis> incr mykey(integer) 10
As the name suggests, it means adding one or subtracting one for a certain key, like in a programming languagemykey++Withmykey--

And there isincrbywithdecrby, you can specify how much you want to add or subtract.

redis> hset mydata name "nick"redis> hset mydata nickname "nicknick"redis> hget mydata name"nick"
H is the meaning of hash, so you can access a field under a value, so that you can use it more diversely, for example, you can define the rule of the key is: post + article id, which can store the number of likes and replies of this article, etc., so you don't have to go to the database every time to re-query.

redis> sadd myset "nick"redis> sadd myset "peter"redis> sadd myset "nick"redis> scard myset(integer) 2
The s of the sadd issetMeaning, this waysetRefers to the one that has been learned about data structuresset, there will be no duplicate content in it.

redis> lpush mylist "a"redis> lpush mylist "b"redis> rpush mylist "c"redis> lrange mylist 0 -11) "b"2) "a"3) "c"redis> lset mylist 0 "d"redis> lrange mylist 0 -11) "d"2) "a"3) "c"
The data structure here is:list, you can choose to push the value from the left or right, and the corresponding command islpushwithrpushlsetIt specifies what the value of an index is.

lrangeYou can print out the values of the specified range, yesThis form, represents the last value.

The good thing about Redis is that it is very fast, so if you encounter some situations where you need to be fast, you can consider seeing if Redis can help you, and here are a few examples of what I have actually used.

In fact, the principle of short ** is very simple, that is, after doing a series of calculations on the original ** (such as hash algorithm) to get a short string, the number of bits or what symbols you want to decide, and then store this set of correspondence in the database, when others query the corresponding key, you will be redirected to the corresponding **.

Because it's a one-to-one relationship with this key-value, it's a good fit for Redis.

If you don't use a key-value cache like Redis, you have to query it from the database every time. It's fine if the amount of data is small, but when the amount of data becomes larger, the time will increase and the burden on the database will increase, so I think it is a good choice to introduce a layer of cache between the database and the logical layer.

The process of implementation is also very simple, the user adds a short **, and the system calculates that abc123 corresponds toWrite key=abc123, value= into the database as above, but it is stored in redis When a user clicks: abc123 this**,Go to redis to check if there is this key,Redirect to the corresponding **If not,I have to go to the database to check,After checking, remember to write a copy to redis If your data has a lot of data,And don't want to spend a lot of money to prepare a large memory redis Server (the database is stored on a hard disk, Redis is stored in memory, and the database will be much cheaper in terms of storage cost), you can use RedisexpireThis feature.

When you're storing data, you can add a new oneexpire timeWhen this time is up, the key will be automatically cleared. For example, the short expiration can be set to 7 days, and it will be automatically deleted if it has not been accessed by any user for 7 days.

The advantage of this is that you can reduce the amount of memory used, and only keep some hot data in Redis, and other less popular and infrequently accessed data in the database, and then write to Redis when it is accessed.

In fact, the short ** service mentioned above, in addition to the function of shortening**, there is another important point, that is: statistical data. For example, Google Short** will provide you: the number of visits, charts, what device to use, etc., these are the core of the Short** service.

If you want to do this function, then you have to record every request, or at least record the content of the request (what mobile phone is used, time point, IP) so that the data can be shown to the user.

If there is a database and the read is read from the database every time, it will cause some performance problems, such as every time you refresh the statistics page, you have to re:select conut(*)from short_url whereOnce, you can catch a total of how many people visited.

Remember what we mentionedincrIs it? That's not where it comes in handy! You can define the format of the key, for example: abc123:visit represents the total number of visits to abc123, and then, as long as every request is executed:incr abc123:visit,This key is the number you want.,Just read it from Redis in the future.。

In addition to this, let's say you want to provide the number of duplicate IP visits , mentioned earliersetIt's a good fit. You can throw the ** IP of each request into a set, as long as you use itscardYou can know how many duplicate IPs there are, which is very convenient, right?

I once did a project with the following requirements:

Open to users at 12 noon**, and after answering a question, they will see their rankings (sorted by answering time), and only the top 300 will have prizes according to their ranking, and then you can think about where you need to interact with the database.

When entering**, you should first check whether there are more than 300 people, and if so, it will prompt the end of the activity (select count(*) and then check whether the user has answered the question, and if you have answered the question, the ranking will be displayed (select ..where id=..If you haven't answered the question, the answer page will be displayed, and the user name (insert into ..) will be displayed after the answer is finishedid=..Since only the first 300 winners of this event have prizes, it is estimated that if there are 10,000 users, the event may be over in 10 seconds!

It can be a bit overwhelming to have to have so many queries in 10 seconds for your database at the same time, and on closer inspection, you can see that there are many places where you don't need to do it with a database, or even better if you do it with Redis!

For example, you can plan it like this:

Use a key:isover to store whether the activity is over, use account as a key, and store the user's rank in it, and the above process can be rewritten as:

When entering**, go to redis to read isover, check whether the activity is over, check whether the user has answered the question, see if there is any data in the key of the user account of redis, if you have not answered the question and finish answering the question, write it to the database, and write the ranking to redis If the ranking of this user is >=300, setting isover = true originally required three operations on the database, but now it is reduced to only the most necessary one, and the rest can be handled by redis. And because Redis is a database that uses memory to store data, the processing speed is very fast! In addition, we don't have many keys (just more than 10,000 keys), and we use very little memory.

In this way, with the help of Redis, the problem that the original database load is too heavy and may be slow or even hang down can be solved smoothly.

If the next time you have a project with a lot of users, or need to return data quickly, but you are afraid that the database will not be able to hold up, you may want to think about whether you can import Redis, or other services that are also cached. In fact, in many cases, if cached is used properly, it can reduce the burden on many databases and speed up the response.

Related Pages