darkorsa / cordo-gateway
API调用网关
Requires
- ext-redis: ^5.0
- cache/doctrine-adapter: ^1.0
- filp/whoops: ^2.3
- guzzlehttp/guzzle: ^7.0
- guzzlehttp/psr7: ^1.7
- hassankhan/config: ^2.0
- http-interop/http-factory-guzzle: ^1.0
- laminas/laminas-mail: ^2.10
- los/los-rate-limit: ^3.1
- middlewares/client-ip: ^2.0
- middlewares/filesystem: ^2.0
- middlewares/image-manipulation: ^2.0
- monolog/monolog: ^2.1
- myclabs/php-enum: ^1.7
- nikic/fast-route: ^1.3
- php-di/php-di: ^6.2
- php-http/cache-plugin: ^1.7
- php-http/curl-client: ^2.1
- php-http/discovery: ^1.7
- psr/http-server-middleware: ^1.0
- relay/relay: ^2.1
- rollbar/rollbar: ^2.1
- symfony/dotenv: ^5.0
- tuupola/cors-middleware: ^1.1
Requires (Dev)
- nunomaduro/phpinsights: ^1.7
- phpstan/phpstan: ^0.11.2
- symfony/var-dumper: ^4.2
This package is auto-updated.
Last update: 2024-09-21 22:20:54 UTC
README
Cordo API网关 - 保护、缓存、分析和监控。
它是做什么的?它是用来做什么的?
API网关是一种API管理工具,充当反向代理,位于客户端和后端服务(或服务集合)之间。
最常见的使用案例
- 防止过度使用和滥用
- 分析和监控
- 将多个API调用合并为一个以优化
- 缓存
需求
- PHP 7.4.0或更高版本
- Apache/Nginx
- PHP Redis扩展(用于请求缓存和速率限制的nosql数据库)
安装
首先确保您已安装了Redis扩展。要检查它,请运行
$ php -i |grep redis
如果其中任何一个缺失,您可以从PECL存储库中安装它
$ sudo pecl install redis
# restart PHP
$ sudo service php7.4-fpm restart
创建您的新项目文件夹,并在该文件夹中输入
$ composer create-project darkorsa/cordo-gateway ./
然后复制.env_example
文件,将其重命名为.env
,并使用您的配置数据完成它。
用法
API密钥
首先在.env
文件中设置您的API_KEY
,这将强制在每个请求中发送带有API_KEY
值的X-Api-Key
头。
您可以通过在public/index.php中注释掉ApiKeyMiddleware
中间件来禁用此功能。
$router->addMiddleware(new ApiKeyMiddleware()); // comment this line
请注意,X-Api-Key还可以用于速率限制功能。
定义路由
由于API网关是目标API的代理,因此您需要注册路由以处理即将到来的请求。这可以在public/index.php中完成
(new App\UsersRoutes($router, $container, 'https://apiurladdress.com'))->register();
将您的路由类放置在app/文件夹的任何位置。
路由类的示例
<?php declare(strict_types=1); namespace App; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Cordo\Gateway\Core\Application\Service\Register\RoutesRegister; class UsersRoutes extends RoutesRegister { public function register(): void { $this->router->addRoute( 'GET', "/users", function (ServerRequestInterface $request, array $params): ResponseInterface { return $this->cacheRequest($request, '/users', 3600, []); } ); $this->router->addRoute( 'POST', "/users", function (ServerRequestInterface $request, array $params): ResponseInterface { return $this->sendRequest($request, '/users', []); } ); } }
在上面的示例中,有两个端点的定义。一个是获取用户数据(GET),另一个是添加新用户(POST)。
CacheRequest
方法将调用目标API并将结果缓存到内存(Redis)中,持续指定的时间。在此示例中为1小时(3600秒)。在缓存无效之前,不会向目标API发出任何请求。
SendRequest
方法将简单地使用原始请求中的所有查询和表单参数调用目标API。
速率限制
您可以在指定时间内限制对API的请求,以防止请求洪水/ API抓取。为此,在config/los_rate_limit.php文件中设置适当的配置设置。
速率限制配置设置的解释这里。
待办事项
- 简单的请求记录器用于分析
安全性
如果您发现任何与安全相关的漏洞,请通过电子邮件dkorsak@gmail.com而不是使用问题跟踪器。
致谢
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。