API Gateway——KONG简单入门

一、简介

Kong,是由Mashape公司开源的,基于Nginx的API gateway。

二、特点

可扩展:支持分布式

模块化 功能:授权、日志、ip限制、限流、api 统计分析(存在商业插件Galileo等、也可自己研发)、请求转化、跨域(CORS)、其他功能通过lua编写插件实现。

三、调用流程

《API Gateway——KONG简单入门》

Once Kong is running, every request being made to the API will hit Kong first, and then it will be proxied to the final API. In between requests and responses Kong will execute any plugin that you decided to install, empowering your APIs. Kong is effectively going to be the entry point for every API request.

译文:Kong启动之后,每个请求先经过Kong,然后由Kong代理 访问最终的API。在请求和响应之间,Kong可以执行任何已配置的插件,达到增强APIs的目的。Kong作为每个API请求的入口。

四、Kong技术架构图

《API Gateway——KONG简单入门》

五、测试环境搭建

1 安装kong

https://getkong.org/install/

2 postgresql安装配置

http://www.ruanyifeng.com/blog/2013/12/getting_started_with_postgresql.html

kong的postgresql数据库连接命令:psql -U kong -d kong -h 127.0.0.1 -p 5432

3 kong配置

https://getkong.org/docs/0.9.x/configuration/

4 kong启动

kong start -c /etc/kong/kong.conf –vv

遇到错误:Error: /usr/local/share/lua/5.1/pgmoon-mashape/init.lua:239: missing password, required for connect

解决方法:检查配置文件的是否存在pg_password配置。

六、使用示例

说明:Kong Admin API 默认口为8001

1 在kong中新增api

1.1命令

curl -i -X POST \

–urlhttp://localhost:8001/apis/\

-d ‘name=getTeacherById’ \

-d ‘upstream_url=http://www.daydays.com/‘ \

-d ‘request_path=/**/**/teacher.do’

1.2 原接口请

curl -i -X GET \

–urlhttp://www.daydays.com/**/**/teacher.do?fmid=1031

1.3 通过kong进行接口请求

curl -i -X GET \

–urlhttp://localhost:8000/**/**/teacher.do?fmid=1031

2 增加限速插件

2.1 命令

curl -X POSThttp://localhost:8001/apis/getTeacherById/plugins\

–data “name=rate-limiting” \

–data “config.second=2” \

–data “config.minute=2” \

–data “config.hour=10000”

2.2 访问频率超过限制后,接口返回结果如下图:

《API Gateway——KONG简单入门》

3 访问控制

3.1 添加key-auth插件,命令如下:

curl -i -X POST \

–urlhttp://localhost:8001/apis/getTeacherById/plugins/\

–data ‘name=key-auth’

此时直接访问接口,将返回以下错误:

《API Gateway——KONG简单入门》

3.2 增加消费者:

curl -i -X POST \

–urlhttp://localhost:8001/consumers/\

–data “username=daydaysTeachApp”

《API Gateway——KONG简单入门》

3.3 为消费者配置证书

curl -i -X POST \

–urlhttp://localhost:8001/consumers/daydaysTeachApp/key-auth/\

–data ‘key=daydaysTeachApp_randomNum123456’

通过key访问请求

curl -i -X GET   –urlhttp://localhost:8000/**/**/teacher?fmid=1031\

“apikey: daydaysTeachApp_randomNum123456”

4 在kong中删除api

curl -i -X DELETE \

–urlhttp://localhost:8001/apis/getTeacherById

七、参考资料

中文资料介绍:https://www.sdk.cn/news/1596

kong官网:https://getkong.org

github:https://github.com/Mashape/kong/

点赞