Home > PHP Framework > Laravel > body text

How to use middleware to limit request flow in Laravel

王林
Release: 2023-11-03 18:16:47
Original
941 people have browsed it

How to use middleware to limit request flow in Laravel

How to use middleware to limit request flow in Laravel

Introduction:
When we develop web applications, we often encounter the need to limit user requests. Situations where requests are restricted, for example, limiting a certain number of requests to be sent per minute, or limiting the number of concurrent requests for a certain interface, etc. In the Laravel framework, we can implement request flow limiting through middleware. This article will introduce how to use middleware to limit request flow and provide corresponding code examples.

1. Understanding middleware and request flow limiting
Middleware (Middleware) is a mechanism provided by Laravel. It can intervene at various stages of request processing and process, filter or enhance requests. . Request throttling is a mechanism that limits the frequency or number of user requests. It is usually used to control the access speed of resources and protect the stability of the server.

2. Create throttling middleware
In Laravel, you can create a middleware through the Artisan command:
php artisan make:middleware ThrottleRequests

The generated middleware file is located in the app/Http/Middleware directory, for example: ThrottleRequests.php.
Next, we need to implement the request flow limiting logic in the handle method of the middleware, such as the following code:

<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateCacheRateLimiter;
use SymfonyComponentHttpFoundationResponse;

class ThrottleRequests
{
    protected $limiter;

    public function __construct(RateLimiter $limiter)
    {
        $this->limiter = $limiter;
    }

    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
    {
        $key = $request->ip(); // 使用 IP 地址作为限流的关键字
        if ($this->limiter->tooManyAttempts($key, $maxAttempts)) {
            return new Response('Too Many Attempts.', 429);
        }

        $this->limiter->hit($key, $decayMinutes * 60);

        return $next($request);
    }
}
Copy after login

In the above code, we use Laravel The RateLimiter class built into the framework implements the request flow limiting function. The TooManyAttempts method is used to determine whether the request exceeds the maximum allowed number, and if so, a 429 status code is returned; the hit method is used to record the number of requests and set the length of the time window.

3. Register middleware
To make the middleware we create effective, we need the $middleware array in the app/Http/Kernel.php file Register middleware in . Find the file and add the following code:

protected $routeMiddleware = [
    // ...
    'throttle' => AppHttpMiddlewareThrottleRequests::class,
];
Copy after login

4. Use middleware for request current limiting
Through the above steps, we have successfully created a request current limiting middleware and completed the middleware register. Next, we can use the middleware in route definitions or controllers.

  1. Use middleware in route definition:

    Route::middleware('throttle:10,1')->get('/test', function () {
     return 'Hello, Laravel!';
    });
    Copy after login

    In the above code, we apply throttle middleware to /test Routing allows up to 10 requests per minute, and after reaching the maximum number of requests, the user will receive a 429 status code.

  2. Using middleware in the controller:

    class TestController extends Controller
    {
     public function __construct()
     {
         $this->middleware('throttle:10,1');
     }
    
     public function index()
     {
         return 'Hello, Laravel!';
     }
    }
    Copy after login

    With the above code, we apply the throttle middleware to TestController The index method in the controller.

    Summary:
    This article introduces how to use middleware in Laravel to limit request flow, and provides corresponding code examples. By using current-limiting middleware, we can flexibly control the frequency and number of user requests, thereby protecting the stability and security of the server. In actual web development, request throttling is a very important technology. I hope this article can be helpful to everyone. Finish

    The above is the detailed content of How to use middleware to limit request flow in Laravel. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template