上一篇博文我们已经把kong搭建起来了,这一篇主要是介绍一下怎么添加API
一、kong的启动命令
上一篇我们使用命令
kong start
来启动kong,除此之外,kong还有很多启动关闭的命令,如下:
kong reload
kong start
kong stop
kong restart
这些命令见名思意,不用太多解释,可以试一下
二、配置Service
接着我们用kong提供的admin API 接口来创建一个Service (在网上搜的其他版本是 localhost:8001/api/ ,kong的新版本把api去掉了,换成了services和routes),我这里用的是新版本,所以是services
curl -i -X POST \
--url http://localhost:8001/services/ \
--data 'name=example-service' \
--data 'url=http://mockbin.org'
如果返回信息跟下面差不多就是创建成功了,上面的这个代码的意思是:创建一个叫example-service的服务,这个服务的上游url是 http://mockbin.org , 就是你如果在kong里面访问这个服务,kong就会代理帮你去访问 mockbin.org
HTTP/1.1 201 Created
Content-Type: application/json
Connection: keep-alive
{
"host":"mockbin.org",
"created_at":1519130509,
"connect_timeout":60000,
"id":"92956672-f5ea-4e9a-b096-667bf55bc40c",
"protocol":"http",
"name":"example-service",
"read_timeout":60000,
"port":80,
"path":null,
"updated_at":1519130509,
"retries":5,
"write_timeout":60000
}
三、配置路由
接下来,为上面创建的service配置路由
curl -i -X POST \
--url http://localhost:8001/services/example-service/routes \
--data 'hosts[]=example.com'
路由的话一般有三种: host 、method 跟 path
上面是配置了host, 意思是你带个example.com的host访问 kong ,kong 就会代理访问之前创建的那个名字叫example-service 服务,不管是创建Service,还是配置路由,这里都是管理,所以用的端口都是8081。
同样,如果返回的是201,created等字段就表示配置路由成功
四、访问
接下来我们访问一下试试:
curl -i -X GET \
--url http://localhost:8000/ \
--header 'Host: example.com'
这里我们带 example.com 这个host访问,注意,这里是访问,所以是8000端口,而不是之前的8001!
这样就能返回 http://mockbin.org 网址的信息
如果不带这个host
curl -i -X GET \
--url http://localhost:8000/
这样的话,就会提示没有匹配的路由。
这样我们就能够使用kong代理访问了。因为中间加了Kong这一层,所以也可以做一下限流,路由,api管理等工作,kong的插件还是比较多的,而且能够让编程者自己写插件,具有很好的灵活性,下一篇博文讲解一下如何添加kong插件