在ThinkPHP API框架中,實現接口限流策略可以通過以下幾種方法:
創建一個自定義的中間件,例如LimitMiddleware
,然后在其中實現限流邏輯。在中間件的handle
方法中,可以使用think\facade\Cache
來存儲限流計數器。以下是一個簡單的示例:
namespace app\middleware;
use think\facade\Cache;
use think\Request;
class LimitMiddleware
{
public function handle(Request $request, \Closure $next)
{
$key = 'api_limit_' . $request->ip();
$limit = 10; // 每分鐘最多請求次數
$expire = 60; // 時間窗口為60秒
if (Cache::has($key)) {
$count = Cache::get($key);
if ($count >= $limit) {
return json(['error' => '請求過于頻繁,請稍后再試'], 429);
}
} else {
Cache::set($key, 1, $expire);
}
Cache::inc($key);
return $next($request);
}
}
接下來,將這個中間件添加到route/api.php
文件中:
Route::middleware(['limit'])->group(function () {
Route::get('some_api', 'SomeController@index');
});
在application/common.php
文件中,添加一個全局輔助函數limit
,用于實現限流邏輯:
if (!function_exists('limit')) {
function limit($key, $limit, $expire)
{
return Cache::has($key) ? Cache::get($key) + 1 : 1;
}
}
然后,在控制器中使用這個全局輔助函數:
namespace app\controller;
use think\Controller;
class SomeController extends Controller
{
public function index()
{
$key = 'api_limit_' . request()->ip();
$limit = 10; // 每分鐘最多請求次數
$expire = 60; // 時間窗口為60秒
if (limit($key, $limit, $expire) > $limit) {
return json(['error' => '請求過于頻繁,請稍后再試'], 429);
}
// 處理請求邏輯
}
}
這兩種方法都可以實現接口限流策略。你可以根據自己的需求和項目結構選擇合適的方法。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。