This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Redis is really a very good technology, it can be very good in a certain extent to solve the instantaneous concurrency of the website, such as commodity buying seconds to kill and other activities.

The reason why Redis can solve high concurrency is that it can directly access memory, whereas in the past we used database (hard disk), improve access efficiency, solve the database server pressure.

Memcache can only store strings, whereas Redis stores a wide variety of types (strings, lists, sets, etc.). However, Redis can store 1 GB. The most important thing is that memcache is not as safe as Redis. When the server fails or unexpectedly shuts down, redSI will back up the data in the memory to the hard disk, while MEMCA Che lost everything it stored; This also shows that memcache is not suitable for use as a database, but can be used for caching.

The following uses Redis to solve instant kill activities to illustrate:

The following program simulates 20 people rushing into the page for seconds killing, and only 10 people can successfully kill seconds. We put the users who come first into the Redis queue, and when the number of users in the queue reaches 10, the users will switch to the end of seconds killing page. We use random numbers to represent different users.

The procedure is as follows: here is just a simple simulation of Redis, the specific application still needs to design the mode by ourselves.


      
    $redis = new Redis();
    $redis->connect("127.0.0.1".6379);
    $redis_name = "miaoshaceshi";
    $num = 10;
    // Get the length of the Redis list
    $len = $redis->llen($redis_name);
    if($len < $num) {$uuid = mt_rand(100000.999999);
        $redis->rpush($redis_name.$uuid);
        echo "Seckill succeeded!";
    }else{
        echo "Sorry I'm late!";
    }
 
    // $r = $redis->lpop("miaoshaceshi");
    // var_dump($r);
 
? >
Copy the code

I use Postman here to simulate concurrent testing of the above code. The results are shown below:

If you are interested, you can try it yourself.

Use the postman to simulate concurrent requests, of course, this is wrong, postman is order request, effect is about the same, of course, concurrent requests and of course there are other ways of dealing with, for example, you can be restrictions on the front end, snap button allows only click once, interface does not return before the data are not allowed to click again, and so on, This depends on the logic of your own project, but Redis is still a great tool for dealing with snap ups to increase server performance

This is the general principle of Redis handling high concurrency, but of course there are differences in practice.

For good suggestions, please enter your comments below.

Welcome to my blog guanchao.site

Welcome to applets: