PHPackages                             tinywan/limit-traffic - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. tinywan/limit-traffic

ActiveLibrary[Caching](/categories/caching)

tinywan/limit-traffic
=====================

limiting and controlling traffic for webman plugin

v1.0.0(10mo ago)181.9k1[3 issues](https://github.com/Tinywan/webman-limit-traffic/issues)MITPHP

Since Mar 30Pushed 10mo ago1 watchersCompare

[ Source](https://github.com/Tinywan/webman-limit-traffic)[ Packagist](https://packagist.org/packages/tinywan/limit-traffic)[ RSS](/packages/tinywan-limit-traffic/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (3)Versions (7)Used By (0)

based on lua script limiting traffic for webman plugin
======================================================

[](#based-on-lua-script-limiting-traffic-for-webman-plugin)

[![Latest Stable Version](https://camo.githubusercontent.com/1beac2fe78ce453ae3f361a82d8ff71e10899b75cfdfc58778e7e12369b045ce/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f6c696d69742d747261666669632f76)](https://packagist.org/packages/tinywan/limit-traffic) [![Total Downloads](https://camo.githubusercontent.com/604533d79a6a9ef1a51b163c57449ece38ddec7fa0470b6aa7362915e0c34735/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f6c696d69742d747261666669632f646f776e6c6f616473)](https://packagist.org/packages/tinywan/limit-traffic) [![Latest Unstable Version](https://camo.githubusercontent.com/06b3c9e0532648b0090f616b2bda8c42747d3791b35dd34b8db2ec976b63aa81/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f6c696d69742d747261666669632f762f756e737461626c65)](https://packagist.org/packages/tinywan/limit-traffic) [![License](https://camo.githubusercontent.com/add9d8798e21f59b9d90092a91377e17c2be661c9f20c1ff783390cba72ce986/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f6c696d69742d747261666669632f6c6963656e7365)](https://packagist.org/packages/tinywan/limit-traffic)

为防止滥用，你应该考虑对您的 API 限流。 例如，您可以限制每个用户 10 分钟内最多调用 API 100 次。 如果在规定的时间内接收了一个用户大量的请求，将返回响应状态代码 429 (这意味着过多的请求)。

安装
--

[](#安装)

```
composer require tinywan/limit-traffic
```

使用
--

[](#使用)

### 应用中间件

[](#应用中间件)

在 `config/middleware.php` 中添加全局中间件如下：

```
return [
    // 全局中间件
    '' => [
        // ... 这里省略其它中间件
        Tinywan\LimitTraffic\Middleware\LimitTrafficMiddleware::class,
    ],
    // api应用中间件
    'api' => [
        Tinywan\LimitTraffic\Middleware\LimitTrafficMiddleware::class,
    ]
];
```

### 路由中间件

[](#路由中间件)

> 注意：需要 `workerman/webman-framework` 版本 `>= 1.0.12`

我们可以给某个一个或某一组路由设置中间件。例如在 `config/route.php` 中添加如下配置：

```
Route::any('/admin', [app\admin\controller\Index::class, 'index'])
->middleware([Tinywan\LimitTraffic\Middleware\LimitTrafficMiddleware::class]);

// 分组路由
Route::group('/blog', function () {
   Route::any('/create', function () {return response('create');});
})->middleware([Tinywan\LimitTraffic\Middleware\LimitTrafficMiddleware::class]);
```

🔏 返回允许的请求的最大数目及时间
-----------------

[](#-返回允许的请求的最大数目及时间)

返回允许的请求的最大数目及时间，例如：`[100, 600]` 表示在 `600` 秒内最多 `100` 次的 API 调

```
Tinywan\LimitTraffic\RateLimiter::getRateLimit(); // 返回 [100, 600]
```

⚠ 请求限制参考
--------

[](#-请求限制参考)

[![rate-limit.png](./rate-limit.png)](./rate-limit.png)

🔰 响应参数详解
--------

[](#-响应参数详解)

- `X-Rate-Limit-Limit` 同一个时间段所允许的请求的最大数目
- `X-Rate-Limit-Remaining` 在当前时间段内剩余的请求的数量
- `X-Rate-Limit-Reset` 为了得到最大请求数所等待的秒数

自定义自己的 Response
---------------

[](#自定义自己的-response)

> 使用场景

- 每个项目有标准的统一输出，自定义返回内容
- 前后端分离：前端要求返回的 `HTTP状态码`并不是 `429`，而是 `200` 或者其他
- 响应的`body`不是 `{"code":0,"msg":"Too Many Requests"}`，而是 `{"error_code":200,"message":"Too Many Requests"}`等其他内容

### 自定义HTTP状态码

[](#自定义http状态码)

编辑 `config/plugin/tinywan/limit-traffic/app.php` 文件的 `status` HTTP 状态码（默认值是 `429`）

### 自定义限流键

[](#自定义限流键)

编辑 `config/plugin/tinywan/limit-traffic/app.php` 文件的 `limit_key` 限流键（默认值是 `none`）

- `none 代表以ip作为限流键`
- `get.id 代表以get请求的id作为限流键`
- `post.access 代表以post请求的access作为限流键`
- `header.token 代表以header请求的token作为限流键`

### 自定义`body`返回内容

[](#自定义body返回内容)

编辑 `config/plugin/tinywan/limit-traffic/app.php` 文件的 `body` 的字段

**默认选项是**

```
{
	"code": 0,
	"msg": "Too Many Requests",
	"data": null
}
```

**自定义选项参考一**

1、假设`status` HTTP 状态码设置为 `200`

2、假设`body`的数组设为为

```
'body' => [
	'error_code' => 200,
	'message' => '请求太多请稍后重试'
]
```

则响应内容为

```
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

{
	"error_code": 200,
	"message": "请求太多请稍后重试"
}
```

其他的可以根据自身业务自定义即可

Other
-----

[](#other)

```
vendor/bin/phpstan analyse src

vendor/bin/php-cs-fixer fix src
```

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance52

Moderate activity, may be stable

Popularity27

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 87.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~241 days

Recently: every ~302 days

Total

6

Last Release

302d ago

Major Versions

v0.0.5 → v1.0.02025-07-20

### Community

Maintainers

![](https://www.gravatar.com/avatar/b0042e0b68ff6a731ef382a03eecd211736c2d619acc55b2b326988085f72bfb?d=identicon)[Tinywan](/maintainers/Tinywan)

---

Top Contributors

[![Tinywan](https://avatars.githubusercontent.com/u/14959876?v=4)](https://github.com/Tinywan "Tinywan (14 commits)")[![kylin987](https://avatars.githubusercontent.com/u/26080774?v=4)](https://github.com/kylin987 "kylin987 (2 commits)")

---

Tags

controllinglimitingphppluginredisredis-lua-scripttinywantrafficwebmanworkermanpluginlimitwebmantraffic

###  Code Quality

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tinywan-limit-traffic/health.svg)

```
[![Health](https://phpackages.com/badges/tinywan-limit-traffic/health.svg)](https://phpackages.com/packages/tinywan-limit-traffic)
```

###  Alternatives

[rtcamp/nginx-helper

Cleans nginx's fastcgi/proxy cache or redis-cache whenever a post is edited/published. Also provides cloudflare edge cache purging with Cache-Tags.

23817.0k1](/packages/rtcamp-nginx-helper)[thedmsgroup/mautic-dashboard-warm-bundle

Improves the performance of the dashboard by sharing/extending/warming caches.

142.0k](/packages/thedmsgroup-mautic-dashboard-warm-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
