本文主要描述5分钟内掌握和使用Kong API网关。在你开始之前,确认你已安装Kong API网关,具体如何安装请参阅我上一篇文章:安装Kong。
本文你将了解到如何管理Kong。第一,我们将教会你如何访问使用RESTful管理接口,来管理 Services(服务), Routes(路由), Consumers(消费者)和其他。数据通过管理API存储到Kong数据存储层(Kong只支持PostgreSQL and Cassandra,不支持MySQL数据库)。
启动Kong命令:kong start [-c /etc/kong/kong.conf]
停止Kong命令:kong stop
重新加载配置:kong reload
确认Kong已启动成功
如果Kong成功启动默认将监听如下端口:
:8000 on which Kong listens for incoming HTTP traffic from your clients, and forwards it to your upstream services.监听HTTP访问端口
:8443 on which Kong listens for incoming HTTPS traffic. This port has a similar behavior as the :8000 port, except that it expects HTTPS traffic only. This port can be disabled via the configuration file.
:8001 on which the Admin API used to configure Kong listens.监听管理API端口
:8444 on which the Admin API listens for HTTPS traffic.
以上端口都可以在kong.conf文件中进行修改和配置。
Configuring a Service配置服务
1. 使用管理API将你的服务添加到Kong
client调用服务名称example-service,访问http://mockbin.org网站
添加成功后,系统将返回如下Json字符串如下图所示:
id:service_id
retries:访问失败重试5次
2.为服务添加路由 Add a Route for the Service
添加路由的目的就是定义访问服务Service的条件,如下面这个例子,为example-service服务添加路由访问域名example.com
当客户端client通过域名example.com访问Kong将匹配example-service服务返回给客户端。通过管理API创建路由成功后会返回如下Json信息:
3.通过Kong测试访问服务Forward your requests through Kong
HTTP header中定义Host变量值为example.com,Kong自动匹配到example-service服务,转发到http://mockbin.org
启用插件Enabling Plugins
Kong通过插件Plugins实现日志记录、安全检测、性能监控和负载均衡等功能。
下面我将演示一个例子,通过启动apikey实现简单网关安全检验。
1. 配置key-auth插件Configure the key-auth plugin
注意:这个插件接收config.key_names定义参数,默认参数名称 ['apikey']。在HTTP请求中 header和params参数中包含apikey参数,参数值必须apikey密钥,Kong网关将坚持密钥,验证通过才可以访问后续服务。
2. Verify that the plugin is properly configured
如下图所示,访问失败原因请求中没有找到API Key,说明Kong安全机制生效了。
添加消费者Adding Consumers
本例子描述添加Servie服务消费者,定义消费者访问API Key,让他有权限访问example-service。
1. Create a Consumer through the RESTful API
创建消费者Jason
id:消费者id
注意:Kong也接受custom_id 参数当创建消费者时 creating consumers ,这样可以和你自己数据库用户id关联起来。
2. Provision key credentials for your Consumer
为消费者Jason创建一个api key,输入如下命令
3. Verify that your Consumer credentials are valid
访问服务请求http header中增加apikey参数
以上我们例子我们使用管理API增加Services, Routes, Consumers、启用安全机制插件Plugins。