Home>Article>Database> Redis flash sale scenario solution

Redis flash sale scenario solution

尚
forward
2020-05-25 09:02:27 2723browse

Redis flash sale scenario solution

In the development of high-traffic programs, you will inevitably encounter high-concurrency application scenarios. The solution is roughly divided into two directions, message queue and lock.

redis implements a simple version of the message queue core

$key = 'quque'; /** * 秒杀商品数量有限,预先存储到消息队列 */ public function qnquque() { for($i = 1 ; $i<=5 ;$i++) { $redis->lpush($key,$i); } } /** * 这里省略掉业务逻辑处理,默认业务逻辑处理完,出队列 */ public function dequque() { $redis->rpop($key); /** * 这里开始商品购买后的业务逻辑处理 */ }

The message queue is very good for preventing overbought and oversold As a solution, to realize the advanced functions of message queue, you need to use professional message queue tools such as (rabbitmq). User Redis There are still some shortcomings in the user redis implementation of message queue. You can find articles to supplement it by yourself. I won’t outline them one by one here. The biggest problem is still the issue of distributed clusters.

Redis optimistic lock implements the flash killing function

Its advantages are as follows:

The message queue consumes a lot of memory. 10,000 requests require 10,000 operations. Dequeue. It is easy to cause the memory resources to be overwhelmed in an instant

Using the logic of optimistic locking, the CPU consumption is relatively low and the memory resources are small

$redis = new redis(); $result = $redis->connect('127.0.0.1', 6379); $cachekey = $redis->get("cachekey"); $number = 100; //抢购数量 if($cachekey<$number){ $redis->watch("cachekey"); $redis->multi(); //设置延迟,方便测试效果。 sleep(5); //插入抢购数据 $redis->hSet("cachekeyList","user_id_".mt_rand(1, 9999),time()); $redis->set("cachekey",$cachekey+1); $result = $redis->exec(); if($result){ $cachekeyList = $redis->hGetAll("cachekeyList"); echo "恭喜".$cachekeyList."抢购成功!
"; }else{ echo "再接再厉"; exit; } }

For more redis knowledge, please pay attention toredis introductory tutorialcolumn.

The above is the detailed content of Redis flash sale scenario solution. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete