PHP actual combat kong to do microservice architecture four (plug-in gateway current limit)
Preface
In order to manage part of the unified business in the process of multi-project management, such as authentication, current limiting, authority, fuse, protocol conversion, unified error code, cache, log, monitoring, alarm, etc.
In this case, we need to find a unified project entrance to set up these services. This unified entrance is the kong gateway introduced in this series of articles.
This article will mainly introduce how to use kong to achieve current limiting.
When writing this article, because Kong is still version 0.13.1, it is embarrassing~~ This article will focus on this version.
kong plugin introduction
The plug-in provides to extend the use of Kong gateway, we can add new functions to the gateway. Plug-ins can be configured to run in various contexts, from specific routing to all services. Plug-ins can provide us with convenient services, such as authentication, rate limiting, or conversion of proxy requests.
Limiting
Plug-in name used:
rate-limiting
orrate-limiting-advanced
Compared with the old version
rate-limiting
, the new versionrate-limiting-advanced
supportshttp https
additional support on the basis of supportgrpc grpcs
Restriction strategy
This is an optional configuration
config.policy
with three values:
- local: The counter is stored on the node in local memory.
- cluster: The counter is stored in the data storage area of Kong [I am PostgreSQL here] and is shared between nodes. (Defaults)
- redis: The counter is stored on the Redis server and shared between nodes.
Scope of application
This plug-in can be added to services, routes, and consumers. If no one is specified, it will be a global plug-in and will take effect on every request.
Source code
<?php
/**
* 注册服务
* @author: 飘逸的罗伯特
*/
//api注册
$api_data = [
'name' => 'goods8',
'uris' => '/goods8',
'methods' => 'GET',
'upstream_url' => 'http://hz12.cn/goods8'
];
var_dump(http_request('http://hz12.cn:8001/apis', $api_data));
//限流设置及注册
$limit = [
'name' => 'rate-limiting',
'config.second' => 2, //每秒钟允许2次
'config.minute' => 3, //每分钟允许3次
//config.hour
//config.day
//config.month
//config.year
];
var_dump(http_request('http://hz12.cn:8001/apis/goods8/plugins', $limit));
/**
* 发送post请求
* @param [string] $url 请求地址
* @param [array] $postdata post参数
* @return [ar] [description]
*/
function http_request($url, $postdata=[]){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
Run example
- Register current limiting plugin
- Run the registered api
- Continue to refresh quickly