当前位置:网站首页>Php+redis realizes the function of canceling orders over time
Php+redis realizes the function of canceling orders over time
2022-07-06 19:04:00 【Student Li】
Business scenario : Second kill case
Second kill business logic : Multiple users rush orders at the same time , adopt mysql The user who gets the row lock enters the page to be paid ( count down ). When the user fails to pay the order and times out, the order will be canceled and the inventory will be returned .
application
thinkphp+redis+workerman( You can customize the command resident )
1、thinkphp install workerman. It's just over here ,thinkphp Find the manual .
2、 Install well redis And expansion . Use the pagoda directly to finish , too .
3、 producer : Users create orders to redis Insert an order data .
$redis = new \Redis();
$redis->connect('127.0.0.1',6379);
//$redis->auth(' password ');//redis If you have a password, add
/**
*seckill_time Is the queue name
*time() + $seckill['pay_time'] Is the expiration timestamp
*$newSeckillOrder->id For the order id, Sure json String store
*/
$redis->zAdd('seckill_time', time() + $seckill['pay_time'], $newSeckillOrder->id);
4、 consumer : Here we need a resident memory to always query whether there is any message in the queue , If you have it, consume it .
workerman
/**
* Every process starts
* @param $worker
*/
public function onWorkerStart($worker)
{
// Prevent time problems
date_default_timezone_set('PRC');
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
//redis password
//$redis->auth(' password ');//redis Add this sentence if you have a password
if($worker->id === 0){
// Other tasks
}
// Second kill processing process
if($worker->id === 1){
echo " Start the second kill task !\n";
//workerman Timer , Once a second .
Timer::add(1, function() use($redis) {
// adopt zRangeByScore Inquire about seckill_time In line 0 Data to the current timestamp .
$res = $redis->zRangeByScore('seckill_time', 0, time());
// There is data
if (count($res) > 0) {
foreach ($res as $k=>$v){
// Process orders ,$res[$k] Orders deposited for producers id Or data .
//.....
// Consume row data in the queue
$redis->zRem('seckill_time', $res[$k]);
}
// Needless to say, I understand this step ! After all, resident memory , We should manage the memory well ~
unset($res);
}
});
}
}
test result :
My side is delay 20 Second consumption
as follows :
After consumption, the queue will be empty ~
The reason for using this scheme :
Maybe some people will ask ,workerman With timer , You can delay the operation directly ? Why is it so unnecessary ?
The reason is simple , If workerman Suddenly something went wrong , Does some data delayed by the timer terminate ? This will cause the lost data to be unable to close the order ! So using redis Delay message queuing , Store data redis in , Even if workerman Something went wrong , Restart workerman You can also consume data that is not consumed !
About redis The problem of data loss during restart requires modifying the configuration as follows .
find appendonly no Change it to appendonly yes
find appendfsync Set to appendfsync everysec
solve redis The problem of losing data after restarting .
Of course, other message oriented middleware can also be used to solve , such as mq, However, the introduction of pagoda user installation is still redis Well !
remember ! Don't use the timer to check the database repeatedly ! Don't use the timer to check the database repeatedly ! Don't use the timer to check the database repeatedly !
Say it three times , The database is under great pressure ~
Of course, this scheme is also applicable to the automatic closing of the group when the group is due , You can make up your brain by yourself .
边栏推荐
- test about BinaryTree
- QPushButton绑定快捷键的注意事项
- From 2022 to 2024, the list of cifar azrieli global scholars was announced, and 18 young scholars joined 6 research projects
- Three years of Android development, Android interview experience and real questions sorting of eight major manufacturers during the 2022 epidemic
- 三年Android开发,2022疫情期间八家大厂的Android面试经历和真题整理
- Jdbc driver, c3p0, druid and jdbctemplate dependent jar packages
- Master Xuan joined hands with sunflower to remotely control enabling cloud rendering and GPU computing services
- 深度循环网络长期血压预测【翻译】
- AcWing 3537. Tree lookup complete binary tree
- 裕太微冲刺科创板:拟募资13亿 华为与小米基金是股东
猜你喜欢
Breadth first traversal of graph
Summary of performance knowledge points
helm部署etcd集群
Self supervised heterogeneous graph neural network with CO comparative learning
Describe the process of key exchange
关于静态类型、动态类型、id、instancetype
[matlab] Simulink the input and output variables of the same module cannot have the same name
提前解锁 2 大直播主题!今天手把手教你如何完成软件包集成?|第 29-30 期
Digital "new" operation and maintenance of energy industry
pychrm社区版调用matplotlib.pyplot.imshow()函数图像不弹出的解决方法
随机推荐
Stm32+esp8266+mqtt protocol connects onenet IOT platform
手写一个的在线聊天系统(原理篇1)
How does crmeb mall system help marketing?
Reptiles have a good time. Are you full? These three bottom lines must not be touched!
Stm32+hc05 serial port Bluetooth design simple Bluetooth speaker
C#/VB.NET 给PDF文档添加文本/图像水印
A wearable arm device for night and sleeveless blood pressure measurement [translation]
Abstract classes and abstract methods
基于蝴蝶种类识别
Wx applet learning notes day01
QPushButton绑定快捷键的注意事项
Certains marchés de l'emploi de Shanghai refusent d'embaucher des personnes qui se rétablissent positives à Xinguan
Penetration test information collection - basic enterprise information
From 2022 to 2024, the list of cifar azrieli global scholars was announced, and 18 young scholars joined 6 research projects
Test technology stack arrangement -- self cultivation of test development engineers
Interface test tool - postman
Nuc11 cheetah Canyon setting U disk startup
视频化全链路智能上云?一文详解什么是阿里云视频云「智能媒体生产」
Specify flume introduction, installation and configuration
RedisSystemException:WRONGTYPE Operation against a key holding the wrong kind of value