背景介绍

之前项目上api的接口用的是自己nginx搭建的反向代理接口,觉得功能性比较查差,故而另辟蹊径找到了kong作为接口网关服务。

工作原理

kong会把所有的后端接口对应的数据放到cassandra数据库中,对外只暴漏自己的接口,这样对于前端的开发人员来说就透明了许多,也方便了许多,后端的运维人员管理起来也方便了许多。

系统环境介绍

系统版本:CentOS release 6.7 (Final)
kong版本:0.9.9
gcc版本:4.8.2 (GCC) 
npm版本:3.8.6
node版本:5.11.1
python版本:Python 2.7.8
cassandra版本:dsc22.noarch
jdk版本:>1.7.25

Kong部署

安装

$ wget https://bintray.com/mashape/kong-rpm-el6-0.9.x/rpm -O bintray-mashape-kong-rpm-el6-0.9.x.repo
$ mv bintray-mashape-kong-rpm-el6-0.9.x.repo /etc/yum.repos.d/
$ yum install kong

启动kong

$ kong start  -c <path_to_config>

检查kong是不是正常启动了,默认不修改配置文件的情况下会报连接不上PostgreSQL,这里先忽略,继续装cassandra

正常启动的话会输出:[OK] Started kong的监听端口:

8000: API请求的代理层。
8001: restful的配置管理API。
8443: 代理HTTPS
7946: 用于和其他Kong节点通讯,支持TCP/UDP流量
7373: 用于本地集群代理通讯

停止kong

$ kong stop

重新加载kong

$ kong reload

重启kong

$ kong restart

cassandra部署

这里就不演示安装了,yum也行,绿色版解压也行。java1.7 或者1.8都可以,注意cassandra3.0必须要jdk1.8版本才行。这里我们由于kong的支持版本是2.x,这里介绍2.x的安装。

yum源添加

 vim /etc/yum.repos.d/datastax.repo
[datastax]
name = DataStax Repo for Apache Cassandra
baseurl = http://rpm.datastax.com/community
enabled = 1
gpgcheck = 0

yum查找软件包

 yum search dsc
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
========================================================= N/S Matched: dsc ==========================================================
dsc1.1.noarch : Meta RPM for installation of the DataStax DSC platform
dsc12.noarch : Meta RPM for installation of the DataStax DSC platform
dsc20.noarch : Meta RPM for installation of the DataStax DSC platform
dsc21.noarch : Meta RPM for installation of the DataStax DSC platform
dsc22.noarch : Meta RPM for installation of the DataStax DSC platform
dsc30.noarch : Meta RPM for installation of the DataStax DSC platform
虽然有3.0,但是目前kong只支持2.2.x ,这里我就安装2.2版本

安装

yum install dsc22

验证cassadnra

估计会报这个错误

 cqlsh
Traceback (most recent call last):
  File "/usr/bin/cqlsh.py", line 160, in <module>
    from cqlshlib import cql3handling, cqlhandling, pylexotron, sslhandling
ImportError: No module named cqlshlib

python2.7部署

cqlsh是cassandra的客户端查询工具 cqlsh客户的工具需要python2.7支持,centos6.x默认是python2.6版本,这里我新安装下python2.7

首先安装 python 工具需要的额外软件包 SSL, bz2, zlib

yum install -y zlib-devel bzip2-devel openssl-devel xz-libs wget

下载python2.7源码包并安装

$ wget http://www.python.org/ftp/python/2.7.8/Python-2.7.8.tar.xz
$ xz -d Python-2.7.8.tar.xz
$ tar -xvf Python-2.7.8.tar
$ cd Python-2.7.8
$ ./configure --prefix=/usr/local
$ make
$ make altinstall

检查 Python 版本并修复yum

$ python2.7 -V
Python 2.7.8
$ mv /usr/bin/python /usr/bin/python2.6.6
$ ln -s /usr/local/bin/python2.7  /usr/bin/python

更改yum环境变量

因为yum使用python2.6 故而要改一下yum的环境,不然yum将没法使用

$ which yum 
/usr/bin/yum
#修改 yum中的python 
将第一行  #!/usr/bin/python  改为 #!/usr/bin/python2.6

安装pip

$ curl  https://bootstrap.pypa.io/get-pip.py | python2.7

解决cqlsh报错问题,下面的步骤可能要耗费很长的时间,建议大家耐心等等

$pip install cqlshlib
$pip install cql
$pip install cassandra-driver
$pip install cqlsh

再次测试数据库情况

 $cqlsh
 Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 2.2.8 | CQL spec 3.3.1 | Native protocol v4]
Use HELP for help.
cqlsh> create schema testschema
   ... with replication = {'class':'SimpleStrategy', 'replication_factor':1};
cqlsh> describe keyspaces;
system  testschema  system_traces
cqlsh> use testschema;
cqlsh:testschema> create table user (
              ... user_id varchar primary key,
              ... first varchar,
              ... last varchar,
              ... age int
              ... );
              ... user_id varchar primary key,
              ... first varchar,
              ... last varchar,
              ... age int
              ... );
cqlsh:testschema> 
cqlsh:testschema> insert into user (user_id, first, last, age) values ('rfroncois', 'ronn', 'francois', 20);
cqlsh:testschema> select * from user;
 user_id  | age | first | last
-----------+-----+-------+----------
 rfroncois |  20 |  ronn | francois

Kong 配置

小编发现kong的配置文件总计三处

/etc/kong/kong.conf.default
/usr/local/kong/kong.conf
/usr/local/share/lua/5.1/kong/templates/kong_defaults.lua

最开始的时候,小编装好数据库和kong,启动kong的时候,修改了/etc/kong/kong.conf.default的配置连接数据库的类型为cassandra,启动的时候死活就是连不上啊,报的还是连不上PostgreSQL数据库,而且每次重启kong服务后,修改后的配置文件被重置了。真实奇葩,猜想必然这个配置文件不是主配置文件啊。 /usr/local/share/lua/5.1/kong/templates/kong_defaults.lua----->主配置文件,那咱就来看看这个文件的具体内容吧。

return [[
--安装路径
prefix = /usr/local/kong/
--日志等级
log_level = notice
--默认插件
custom_plugins = NONE
--发送匿名使用数据,如错误堆栈跟踪,以帮助提高kong。Default: on
anonymous_reports = on
--监听地址,客户端访问地址。Default: 0.0.0.0:8000
proxy_listen = 0.0.0.0:8000
--如果启用ssl,kong将接受https请求的地址和端口。Default: 0.0.0.0:8443
proxy_listen_ssl = 0.0.0.0:8443
--管理接口地址,有必要保密。Default:0.0.0.0:8001
admin_listen = 0.0.0.0:8001
--nginx进程数,如果不会设置,设置成自动,会自动检测,默认auto等同于cpu核数.Default: auto
nginx_worker_processes = auto
nginx_optimizations = on
--确定nginx是作为守护进程还是作为前台进程运行。Default: on
nginx_daemon = on
--数据库实体的内存缓存大小。接受的单位是k和m,最小推荐值是几个mbs。Default: 128m
mem_cache_size = 128m
--确定nginx是否应该监听proxy_listen_ssl地址上的https流量。如果禁用,nginx将只在proxy_listen上绑定自己,所有ssl设置将被忽略.Default: on
ssl = off
如果启用了ssl,proxy_listen_ssl地址的绝对路径。如果没有指定,并且ssl被启用,kong将生成默认的证书和密钥。Default: none
ssl_cert = NONE
--如果启用了ssl,proxy_listen_ssl地址的ssl密钥的绝对路径。Default: none
ssl_cert_key = NONE
--确定该节点将使用哪个postgresql或cassandra作为其数据存储区。接受的数据库类型是postgres和cassandra。属于同一个集群的所有kong节点必须连接到同一个数据库。Default: postgres
database = cassandra
--postgres服务器的主机
pg_host = 127.0.0.1
--postgres服务器的端口
pg_port = 5432
--数据库连接。必须存在
pg_database = kong
--postgres用户
pg_user = kong
--postgres用户的密码
pg_password = NONE
--启用S​​SL连接到服务器
pg_ssl = off
--如果启用pg_ssl,则切换服务器证书验证
pg_ssl_verify = off
--用逗号分隔的联系人列表指向您的cassandra集群。
cassandra_contact_points = 127.0.0.1
--您的节点正在侦听的端口。
cassandra_port = 9042
--密钥空间在您的群集中使用。如果不存在,将被创建。
cassandra_keyspace = kong
--如果是第一次创建密钥空间,请指定一个复制策略。
cassandra_repl_strategy = SimpleStrategy
--指定简单策略的复制因子。
cassandra_repl_factor = 1
--为网络拓扑策略指定数据中心。
cassandra_data_centers = dc1:2,dc2:3
--读取/写入cassandra群集时使用的一致性设置。
cassandra_consistency = ONE
--读/写超时(以毫秒为单位)。
cassandra_timeout = 5000
--启用ssl连接到节点。
cassandra_ssl = off
--如果启用cassandra_ssl,则切换服务器证书验证
cassandra_ssl_verify = off
--用户名
cassandra_username = kong
--密码
cassandra_password = NONE
cluster_listen = 0.0.0.0:7946
cluster_listen_rpc = 127.0.0.1:7373
cluster_advertise = NONE
cluster_encrypt_key = NONE
cluster_profile = wan
cluster_ttl_on_failure = 3600
dnsmasq = on
dnsmasq_port = 8053
dns_resolver = NONE
--当禁用时,每个请求将在一个单独的lua虚拟机实例中运行:所有lua模块将从头开始加载。这对开发插件时采用编辑和刷新方法很有用。据官方说,关闭此指令对
--性能有严重影响,并且从0.11.0以后删除此配置
lua_code_cache = on
--pem格式的lua cosockets的证书颁发机构文件的绝对路径。当启用pg_ssl_verify或cassandra_ssl_verify时,此证书将用于验证kong的数据库连接。
lua_ssl_trusted_certificate = NONE
--在由lua_ssl_trusted_certificate设置的lua cosockets使用的服务器证书链中设置验证深度。
lua_ssl_verify_depth = 1
--设置lua模块搜索路径(lua_path)。在开发或使用未存储在默认搜索路径中的自定义插件时非常有用。
lua_package_path = ?/init.lua;./kong/?.lua
--设置lua c模块搜索路径(lua_cpath)。
lua_package_cpath = NONE
serf_path = serf
]]

再次启动kong看它还报不报错

[root@localhost templates]# kong start
Kong started

kong在命令行的操作演示

1).port:8000 客户端调用api端口,网关对外开放端口。例如:新建一个api,访问path= /test,则访问 http://10.110.2.3:8000/test  
2).port:8001 kong admin api管理端口,可以通过该端口对api、consumer、plugin进行管理,例如:查看名字叫test 这个api配置信息,访问 http://10.110.2.3:8001/apis/test,查看所有api信息,访问 http://10.110.2.3:8001/apis 
3).KONG管理平台,访问 http://10.110.2.3:8888/#/  此端口开通必须安装 kong dashboard。通过此端口,可使用图形界面化管理api、consumer、plugin等。

kong 增加api调用 原有接口调用访问路径: http://192.168.1.100:5105/notice/getNotice 添加调用规则语句: #--url 指定本地的kong访问连接 #--d name 指定添加的api的规则名称 #-d upstream_rul 指定访问原api的host以及端口 #-d request_path 指定请求路径 curl -i -X POST --url http://localhost:8001/apis/ -d 'name=getAannouncementList' -d 'upstream_url=http://192.168.1.100:5105/' -d 'request_path=/notice/getNotice' curl -i -X POST --url http://localhost:8001/apis/ -d 'name=testapi' -d 'upstream_url=http://192.168.1.100:5105/' -d 'request_path=/notice/getNotice'

添加api规则后访问语句: http://192.168.5.250:8000/notice/getNotice

对某个访问规则进行用户验证设置 设置语句语法: #--url 要对那个访问规则进行设置,apis后面对应的是上面设置的api访问规则中设置的name关键字,其余为固定格式 #--data 设置权限访问关键字 curl -i -X POST --url http://192.168.5.250:8001/apis/getAannouncementList/plugins/ --data 'name=key-auth' curl -i -X POST --url http://192.168.5.250:8001/apis/testapi/plugins/ --data 'name=key-auth'

增加一个用户: 设置语句语法: #--url 规定格式 #--data username 设置增加的用户名称 curl -i -X POST --url http://192.168.5.250:8001/consumers/ --data "username=inhomeApp" curl -i -X POST --url http://192.168.5.250:8001/consumers/ --data "username=test"

为消费者添加证书: 设置语句语法: #--url 倒数第二个请求路径为要授予的用户名称 #--data key 设置的密码 curl -i -X POST --url http://192.168.5.250:8001/consumers/inhomeApp/key-auth/ --data 'key=inhomeApp_randomNum123456' curl -i -X POST --url http://192.168.5.250:8001/consumers/test/key-auth/ --data 'key=test_randomNum123456'

通过key访问api请求-- curl -i -X GET --url http://192.168.5.250:8000/notice/getNotice --header "Host: 192.168.5.250:8000" --header "apikey: test_randomNum123456" or http://192.168.5.250:8000/notice/getNotice?apikey=test_randomNum123456

删除api规则 curl -i -X DELETE --url http://192.168.5.250:8001/apis/getAannouncementList 查看kong的所有api规则信息 http://192.168.5.250:8001/apis

搭建kong UI Admin

配置node

下载node绿色版,版本5.11.1 https://nodejs.org/en/blog/release/v5.11.1/ 解压后,追加node中的bin目录到PATH环境变量中即可。

升级GCC版本到4.8

下载4.8源码包并解压

wget http://ftp.gnu.org/gnu/gcc/gcc-4.8.2/gcc-4.8.2.tar.bz2    
 tar -jxvf  gcc-4.8.2.tar.bz2

当然,http://ftp.gnu.org/gnu/gcc 里面有所有的gcc版本供下载,最新版本已经有4.9.2啦.

下载供编译需求的依赖项

参考文献[1]中说:这个神奇的脚本文件会帮我们下载、配置、安装依赖库,可以节约我们大量的时间和精力。

cd gcc-4.8.0       ./contrib/download_prerequisites 

建立一个目录供编译出的文件存放

mkdir gcc-build-4.8.2        
 cd gcc-build-4.8.2

生成Makefile文件

../configure -enable-checking=release -enable-languages=c,c++ -disable-multilib 编译(注意:此步骤非常耗时)

make -j4

-j4选项是make对多核处理器的优化,如果不成功请使用 make

报错

/home/imdb/gcc-4.8.2/gcc-build-4.8.2/x86_64-unknown-linux-gnu/32/libgcc’ 
make[4]: * [multi-do] 错误 1 make[4]: Leaving directory 
/home/imdb/gcc-4.8.2/gcc-build-4.8.2/x86_64-unknown-linux-gnu/libgcc’ 
make[3]: * [all-multi] 错误 2 make[3]: * 正在等待未完成的任务…. 
make[3]: Leaving directory 
/home/imdb/gcc-4.8.2/gcc-build-4.8.2/x86_64-unknown-linux-gnu/libgcc’ 
make[2]: * [all-stage1-target-libgcc] 错误 2 make[2]: Leaving 
directory/home/imdb/gcc-4.8.2/gcc-build-4.8.2’ make[1]: * 
[stage1-bubble] 错误 2 make[1]: Leaving directory 
/home/imdb/gcc-4.8.2/gcc-build-4.8.2’ make: * [all] 错误 2

解决办法:sudo yum -y install glibc-devel.i686 glibc-devel

安装

sudo make install

安装Kong Dashboard

官方文档 https://github.com/PGBI/kong-dashboard 这里面有一个放长重要的东西,非常重要,小编这个坑足足迈了3次才迈过去。 Compatibility matrix

Kong-Dashboard versions Kong versions Node versions
1.x.x 0.6.x, 0.7.x, 0.8.x, 0.9.x
2.x.x 0.10.x
3.x.x 0.9.x, 0.10.x, 0.11.x >= 6.0.0

命令行安装

  • Install Kong Dashboard npm install -g kong-dashboard@v1
  • Start Kong Dashboard kong-dashboard start
  • To start Kong Dashboard on a custom port kong-dashboard start -p [port]
  • To start Kong Dashboard with basic auth kong-dashboard start -a user=password 这样启动会在后台运行,断掉终端进程还在 nohup kong-dashboard start -p 8080 -a xin=sir >kong-dashboard.log &

源码安装

下载代码
git clone https://github.com/PGBI/kong-dashboard.git
cd kong-dashboard
git checkout 1.0
构建
npm install
npm run build
启动
npm start
启动在某个端口或设置权限
npm start -- [-p port] [-a user=password]

配置kong UI admin

访UI Admin

http://192.168.5.250:8080/#/

配置UI Admin

如果kong有用户名和密码那么选择Basic auth,配置注意地址(kong的管理地址,默认为http://kong server机器或绑定的域名:8001)后面不要多加"/"如下图 否则点击API会出现not found api之类的提示,当然也要确保kong server正常运行中

创建API

新增API与使用新增的API时,需要注意如果需要使用地址方式指向api即 需要勾选strip-request path 如果使用head中带请求地址的方式,需要在head中带 X-Host-Override post.demo (即request host) 访问kong:8000/version/getVersion 就能看到你想看的画面啦。

为某个api设置权限认证

创建用户

通过key访问url

http://192.168.5.250:8000/notice/getNotice?testname=keyauth 不出意外能看到你想看到的画面

黑白名单设置

设置限流策略

可配置项: year:年 month: 月 day: 天 minute:分钟,这里我们配置3,表示每分钟不能超过3次调用。 Second: 秒 计算频率的维度:月/天/分钟/秒, 假如同时配置多个维度,会同时生效。 验证:连续一分钟内请求,第四次,报错 { "message": "API rate limit exceeded" } 根据年、月、日、时、分、秒设置限流规则,多个限制同时生效。 比如:每天不能超过10次调用,每分不能超过3次。 当一分钟内,访问超过3次,第四次就会报错。 当一天内,访问次数超过10次,第十一次就会报错。

为kong-dashboard设置访问权限

启动方式:

[root@Kong ~]# kong-dashboard start -a xinsir=521

故障申报

问题一: 可能会出现的问题,当使用源码安装的时候,启动后访问8080端口如果出现Not Found,这个多半是因为没有构建npm造成的。 问题二: cassandra数据库启动后自动down掉,日志报错报错说jdk需要大于1.7_25这个升级jdk就可以了。

kong服务监控

/status
{
	"server":  有关nginx http/s服务器的度量。
		{
			"connections_handled":2588, 处理的连接总数。一般来说,除非达到一定的资源限制,否则参数值与接受的值相同。
			"connections_reading":0, kong读取请求头的当前连接数。
			"connections_active":4, 当前活动客户端连接的数量,包括等待连接。
			"total_requests":2585,  客户端请求的总数。
			"connections_accepted":2588, 接受的客户端连接总数。
			"connections_writing":1, nginx将响应写回客户端的当前连接数。
			"connections_waiting":3 当前正在等待请求的空闲客户端连接数。
		},
	"database": 有关数据库集合的度量。
		{
			"oauth2_credentials":0,
			"jwt_secrets":0,
			"response_ratelimiting_metrics":0,
			"keyauth_credentials":0,
			"oauth2_authorization_codes":0,
			"acls":0,
			"apis":1,
			"basicauth_credentials":0,
			"consumers":0,
			"ratelimiting_metrics":0,
			"oauth2_tokens":0,
			"nodes":1,
			"hmacauth_credentials":0,
			"plugins":0
		}
}
/cluster  检索群集状态,返回群集中每个节点的信息。
{
	"data":[
			{
				"address":"192.168.1.205:7946",  节点地址
				"name":"Kong_0.0.0.0:7946_a102f6e6cede4540b1cc6a7a46276986", 节点名称
				"status":"alive"	节点状态
			}
		   ],
			"total":1  节点数
}

使用zabbix获取参数 进行页面监控就可以了

使用https方式安全调用api接口

先去阿里云上购买免费的SSL证书 在产品中找到安全(云盾),选择SSL证书 选择购买证书 选择Symantec的免费SSL证书,有效期为1年 购买后得到一个pem证书和key文件 在kong目录下的ssl中,里面有默认的自签名证书和key,这是不安全的,把他备份后,将阿里云上下载的pem和key放到ssl中,pem后缀改为crt,将文件名改为默认kong-default

修改nginx-kong.conf文件

重启kong和nginx

之前调api路径为 http://192.168.5.250:8000/notice/getNotice 配置完https后为(绑定了域名) https://api.example.com:8443/notice/getNotice