


laravel+Redis simply implements high-concurrency processing of queues that pass stress testing
This article mainly introduces the high concurrency processing of laravel Redis's simple implementation of queue passing the stress test. It has a certain reference value. Now I share it with you. Friends in need can refer to it
flash sale activity
In general online malls, we are often exposed to some highly concurrent business conditions, such as our common flash sales and other activities.
In these businesses, we often need to process some request information Filtering and product inventory issues.
A common situation in requests is that the same user issues multiple requests or contains malicious attacks, as well as the repurchase of some orders.
In terms of inventory, you need to consider the situation of oversold.
Let’s simulate a simple and available concurrent processing.
Go directly to the code
Code process
1. Simulate user request and write the user into the redis queue
2. Take out one from the user Request information for processing (you can do more processing in this step, request filtering, order repurchase, etc.)
3. The user places an order (payment, etc.) to reduce inventory. Two methods are used for processing below. One uses the single-threaded atomic operation feature in Redis to make the program operate linearly and maintain data consistency.
The other is to use transactions for operations, which can be adjusted according to the business. I will not describe them one by one here.
The actual business situation is more complicated, but it is more due to the expansion of basic ideas.
<?php namespace App\Http\Controllers\SecKill; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redis; class SecKillControllers extends Controller { public function SecKillTest() { ///在此之前我们已经将一千过用户写入了redis中了 $num = Redis::lpop('user_list'); ///取出一个用户 /// ///一些对请求的处理 /// if (!is_null($num)) { ///将需要秒杀的商品放入队列中 $this->AddGoodToRedis(1); ///需要注意的是我们如果写的是秒杀活动的话,需要做进一步的处理,例如设置商品队列的缓存等方式,这里就实现了 ///下订单减库存 $this->GetGood(1,$num); } } public function DoLog($log) { file_put_contents("test.txt", $log . '\r\n', FILE_APPEND); } /** * 重点在于Redis中存储数据的单线程的原子性,!!!无论多少请求同时执行这个方法,依然是依次执行的!!!!! * 这种方式性能较高,并且确保了对数据库的单一操作,但容错率极低,一旦出现未可预知的错误会导致数据混乱; */ public function GetGood($id,$user_id) { $good = \App\Goods::find($id); if (is_null($good)) { $this->DoLog("商品不存在"); return 'error'; } ///去除一个库存 $num = Redis::lpop('good_list'); ///判断取出库存是否成功 if (!$num) { $this->DoLog("取出库存失败"); return 'error'; } else { ///创建订单 $order = new \App\Order(); $order->good_id = $good->good_id; $order->user_id = $user_id; $order->save(); $ok = DB::table('Goods') ->where('good_id', $good->good_id) ->decrement('good_left', $num); if (!$ok) { $this->DoLog("库存减少失败"); return; } echo '下单成功'; } } public function AddUserToRedis() { $user_count = 1000; for ($i = 0; $i < $user_count; $i++) { try { Redis::lpush('user_list', rand(1, 10000)); } catch (Exception $e) { echo $e->getMessage(); } } $user_num = Redis::llen('user_list'); dd($user_num); } public function AddGoodToRedis($id) { $good = \App\Goods::find($id); if ($good == null) { $this->DoLog("商品不存在"); return; } ///获取当前redis中的库存。 $left = Redis::llen('good_list'); ///获取到当前实际存在的库存,库存减去Redis中剩余的数量。 $count = $good->good_left - $left; // dd($good->good_left); ///将实际库存添加到Redis中 for ($i = 0; $i < $count; $i++) { Redis::lpush('good_list', 1); } echo Redis::llen('good_list'); } public function getGood4Mysql($id) { DB::beginTransaction(); ///开启事务对库存以及下单进行处理 try { ///创建订单 $order = new \App\Order(); $order->good_id = $good->good_id; $order->user_id = rand(1, 1000); $order->save(); $good = DB::table("goods")->where(['goods_id' => $id])->sharedLock()->first(); //对商品表进行加锁(悲观锁) if ($good->good_left) { $ok = DB::table('Goods') ->where('good_id', $good->good_id) ->decrement('good_left', $num); if ($ok) { // 提交事务 DB::commit(); echo'下单成功'; } else { $this->DoLog("库存减少失败"); } } else { $this->DoLog("库存剩余为空"); } DB::rollBack(); return 'error'; } catch (Exception $e) { // 出错回滚数据 DB::rollBack(); return 'error'; //执行其他操作 } } }
AB test
Here I used apache bench to test the code
Calling the code in
AddUserToRedis() 方法将一堆请求用户放进redis队列中 先看库存
这里设置了一千个库存 开始压力测试
向我们的程序发起1200个请求,并发量为200
Here we completed 1200 requests, of which 1199 were marked as failed. This is because apache bench will use the content of the first request response as the benchmark.
If the content of subsequent request responses is inconsistent, it will be marked as a failure. If you see that the number of marks in length is not correct, it can basically be ignored. We The request was actually completed.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Solution to the configuration error of fastcgi_param in the nginx configuration file
How to use the wp_head() function in wordpress
The above is the detailed content of laravel+Redis simply implements high-concurrency processing of queues that pass stress testing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.
