使用的軟件
- Unbuntu 虛擬機(有自己的服務器更好)
 - PostgreSQL
 - kong
 - kong-dashboard
 - docker
 - spring boot
 
安裝 PostgreSQL
kong 需要使用到數據庫,目前支持PostgreSQL和Cassandran ,我選擇大象數據庫,安裝過程省略,可以參考這篇文章。
Ubuntu PostgreSQL安裝和配置
安裝完后建一個kong的用戶、密碼為kong、建一個kong 數據庫:
sudo -u postgres psql 進入,提示符變成: postgres=#
postgres=# create user kong with password 'kong'; CREATE ROLE postgres=# CREATE DATABASE kong OWNER kong; CREATE DATABASE postgres=#
至此,PostgreSQL已經安裝和配置好了。
安裝kong
下載kong的源文件,下載地址:https://getkong.org/install/ubuntu/


下載完成之后會有這樣一個文件kong-community-edition-0.11.0.*.deb,cd到這個文件的目錄:
$ sudo apt-get update $ sudo apt-get install openssl libpcre3 procps perl $ sudo dpkg -i kong-community-edition-1.0.2.*.deb
查看kong的版本:
kong version

配置kong
配置文檔在這里:
https://getkong.org/docs/0.9.x/configuration/
復制配置文件:
$ cp /etc/kong/kong.conf.default /etc/kong/kong.conf 
        配置文件(Kong將使用默認設置進行操作。啟動時,Kong會查找可能包含配置文件的幾個默認位置):
cat /etc/kong/kong.conf
cat /etc/kong.conf
打開配置文件,里面可以修改很多配置,修改數據庫連接,用戶名、密碼
pg_host = 127.0.0.1 # The PostgreSQL host to connect to. pg_port = 5432 # The port to connect to. pg_user = kong # The username to authenticate if required. pg_password = kong # The password to authenticate if required. pg_database = kong

數據庫配置(上面已經有了)
kong連數據庫,需要我們在pg上建立密碼為kong的kong用戶,數據庫名也為kong
su - postgres//進入數據庫 -bash-4.2$ psql postgres=# CREATE USER kong WITH PASSWORD 'kong'; CREATE DATABASE kong OWNER kong;//建立數據庫以及用戶
修改kong配置
進入/usr/local/share/lua/5.1/kong/templates目錄,修改kong_defaults.lua里的pg_password=kong,保存
初始化數據庫,執行以下整合命令:
$ kong migrations up -c /etc/kong/kong.conf.default
出錯:
Error: /usr/local/share/lua/5.1/kong/cmd/start.lua:28: [postgres error] could not retrieve current migrations: [postgres error] 致命錯誤: 用戶 "kong" Ident 認證失敗
解決方法:
vi /var/lib/pgsql/9.6/data/pg_hba.conf
修改
把這個配置文件中的認證 METHOD的ident修改為trust,可以實現用賬戶和密碼來訪問數據庫,
即解決psql: 致命錯誤: 用戶 "postgres" Ident 認證失敗 這個問題)
第五步:重啟postgresql服務器使設置生效
#service postgresql-9.6 restart
再重試上面的migrations指令。
好像高版本是使用:
kong migrations bootstrap
執行好后,數據庫會生成很多表,這些是默認但kong數據表,后續可以自定義插件,重新migrations,會生成自定義表

啟動kong :
kong start -c /etc/kong/kong.conf --vv
默認情況下,KONG監聽的端口為:
· 8000:此端口是KONG用來監聽來自客戶端傳入的HTTP請求,並將此請求轉發到上有服務器;(kong根據配置的規則轉發到真實的后台服務地址。)
· 8443:此端口是KONG用來監聽來自客戶端傳入的HTTPS請求的。它跟8000端口的功能類似,轉發HTTPS請求的。可以通過修改配置文件來禁止它;
· 8001:Admin API,通過此端口,管理者可以對KONG的監聽服務進行配置,插件設置、API的增刪改查、以及負載均衡等一系列的配置都是通過8001端口進行管理;
· 8444:通過此端口,管理者可以對HTTPS請求進行監控;
最后、瀏覽器訪問IP:8000,如果出現{"message":"no API found with those values"}
注意點:如果有防火牆的話,最好先關掉防火牆。
kong的日志
[root@localhost logs]# pwd /usr/local/kong/logs [root@localhost logs]# ll 總用量 184 -rw-r--r--. 1 root root 28358 2月 22 18:55 access.log -rw-r--r--. 1 root root 63986 2月 22 18:32 admin_access.log -rw-r--r--. 1 root root 91335 2月 22 18:09 error.log [root@localhost logs]# tail -50f error.log
示例:
打開瀏覽器訪問:localhost:8001,瀏覽器顯示了一大串關於kong的json字符串,則啟動成功。
curl -i http://localhost:8001/

管理端口用rest api對api進行操作,文檔地址:https://getkong.org/docs/0.8.x/admin-api
接口接入kong測試
下面的所有admin api操作,如果成功會寫入postgreSQL中,下面是按照官方的demo操作的,所有操作都是成功的。數據落地到數據庫的,查詢見《Ubuntu PostgreSQL安裝和配置》的第七章節。
示例1:服務轉發
1. Add your Service using the Admin API
Issue the following cURL request to add your first Service (pointing to the baidu) to Kong:
curl -i -X POST \ --url http://localhost:8001/services/ \ --data 'name=baidu-service' \ --data 'url=http://www.baidu.com'
You should receive a response similar to:
HTTP/1.1 201 Created Date: Wed, 13 Feb 2019 03:48:38 GMT Content-Type: application/json; charset=utf-8 Connection: keep-alive Access-Control-Allow-Origin: * Server: kong/1.0.2 Content-Length: 258 { "host": "www.baidu.com", "created_at": 1550029718, "connect_timeout": 60000, "id": "be1ea866-c4b4-46ac-9c92-ff821fb317ab", "protocol": "http", "name": "baidu-service", "read_timeout": 60000, "port": 80, "path": null, "updated_at": 1550029718, "retries": 5, "write_timeout": 60000 }
2. Add a Route for the Service
curl -i -X POST \ --url http://localhost:8001/services/baidu-service/routes \ --data 'hosts[]=baidu.com'
The answer should be similar to:
HTTP/1.1 201 Created Date: Wed, 13 Feb 2019 03:51:19 GMT Content-Type: application/json; charset=utf-8 Connection: keep-alive Access-Control-Allow-Origin: * Server: kong/1.0.2 Content-Length: 346 { "created_at": 1550029879, "methods": null, "id": "d813af89-13fe-4d94-945f-d5bbf4c56a28", "service": { "id": "be1ea866-c4b4-46ac-9c92-ff821fb317ab" }, "name": null, "hosts": ["baidu.com"], "updated_at": 1550029879, "preserve_host": false, "regex_priority": 0, "paths": null, "sources": null, "destinations": null, "snis": null, "protocols": ["http", "https"], "strip_path": true }
Kong is now aware of your Service and ready to proxy requests.
3. Forward your requests through Kong
Issue the following cURL request to verify that Kong is properly forwarding requests to your Service. Note that by default Kong handles proxy requests on port :8000:
curl -i -X GET \ --url http://localhost:8000/ \ --header 'Host: baidu.com'
 

A successful response means Kong is now forwarding requests made to http://localhost:8000 to the url we configured in step #1, and is forwarding the response back to us. Kong knows to do this through the header defined in the above cURL request:
kong完美的實現了接口轉發~
注意注冊時,'hosts', 'uris' or 'methods'三個參數至少有一個必須指定。
示例2:Enabling Plugins
1. Configure the key-auth plugin
To configure the key-auth plugin for the Service you configured in Kong, issue the following cURL request:
curl -i -X POST \ --url http://localhost:8001/services/example-service/plugins/ \ --data 'name=key-auth'
Note: This plugin also accepts a config.key_names parameter, which defaults to ['apikey']. It is a list of headers and parameters names (both are supported) that are supposed to contain the apikey during a request.
2. Verify that the plugin is properly configured
Issue the following cURL request to verify that the key-auth plugin was properly configured on the Service:
curl -i -X GET \ --url http://localhost:8000/ \ --header 'Host: example.com'
Since you did not specify the required apikey header or parameter, the response should be 401 Unauthorized:
duanxz@ubuntu18:~/kong$ curl -i -X GET \ > --url http://localhost:8000/ \ > --header 'Host: example.com' HTTP/1.1 401 Unauthorized Date: Wed, 13 Feb 2019 04:13:09 GMT Content-Type: application/json; charset=utf-8 Connection: keep-alive WWW-Authenticate: Key realm="kong" Content-Length: 41 Server: kong/1.0.2 {"message":"No API key found in request"}
配置好了 key-auth plugin。
示例3:Consumer
配置好了 key-auth plugin后,lets learn how to add consumers to your Service so we can continue proxying requests through Kong。
1. Create a Consumer through the RESTful API
Lets create a user named Jason by issuing the following request:
curl -i -X POST \ --url http://localhost:8001/consumers/ \ --data "username=Jason"
You should see a response similar to the one below:
HTTP/1.1 201 Created Content-Type: application/json Connection: keep-alive { "custom_id": null, "created_at": 1550031667, "username": "Jason", "id": "f23dfd0f-6a43-444d-b628-6137cbdb1e6e" }
Congratulations! You’ve just added your first consumer to Kong.
Note: Kong also accepts a custom_id parameter when creating consumers to associate a consumer with your existing user database.
2. Provision key credentials for your Consumer
Now, we can create a key for our recently created consumer Jason by issuing the following request:
curl -i -X POST \ --url http://localhost:8001/consumers/Jason/key-auth/ \ --data 'key=ENTER_KEY_HERE'
返回:
HTTP/1.1 201 Created Date: Wed, 13 Feb 2019 04:22:30 GMT Content-Type: application/json; charset=utf-8 Connection: keep-alive Access-Control-Allow-Origin: * Server: kong/1.0.2 Content-Length: 149 { "key": "ENTER_KEY_HERE", "created_at": 1550031750, "consumer": { "id": "f23dfd0f-6a43-444d-b628-6137cbdb1e6e" }, "id": "6d6c4792-f295-4f2a-9941-9357d17240d1" }
3. Verify that your Consumer credentials are valid
We can now issue the following request to verify that the credentials of our Jason Consumer is valid:
curl -i -X GET \ --url http://localhost:8000 \ --header "Host: example.com" \ --header "apikey: ENTER_KEY_HERE"

 
        Next Steps
Now that we’ve covered the basics of adding Services, Routes, Consumers and enabling Plugins, feel free to read more on Kong in one of the following documents:
Questions? Issues? Contact us on one of the Community Channels for help!
遇到的問題
如果本機可以訪問8000端口,遠程機器無法通過ip:8000訪問kong,估計是防火牆的問題
CentOS7使用firewalld打開關閉防火牆與端口 1、firewalld的基本使用 啟動: systemctl start firewalld 關閉: systemctl stop firewalld 查看狀態: systemctl status firewalld 開機禁用 : systemctl disable firewalld 開機啟用 : systemctl enable firewalld
ERROR: module ‘socket’ not found:No LuaRocks module found for socket
啟動的時候:
# ./bin/kong start -c ./kong.conf ... ERROR: ./kong/globalpatches.lua:63: module 'socket' not found:No LuaRocks module found for socket ...  
         這是因為編譯kong之后,重新編譯了luarocks,並且將luarocks安裝在了其它位置。重新編譯kong之后解決。
ERROR: function to_regclass(unknown) does not exist (8)
創建數據庫的時候:
# kong migrations up -c ./kong.conf
...
[postgres error] could not retrieve current migrations: [postgres error] ERROR: function to_regclass(unknown) does not exist (8) ...  
         這是因為PostgreSQL的版本太低了,to_regclass在PostgreSQL 9.4及以上的版本中才存在。
yum install https://download.postgresql.org/pub/repos/yum/9.6/redhat/rhel-7-x86_64/pgdg-centos96-9.6-3.noarch.rpm yum install postgresql96 yum install postgresql96-server  
         nginx: [emerg] unknown directive “real_ip_header” in /usr/local/kong/nginx-kong.conf:73
nginx: [emerg] unknown directive "real_ip_header" in /usr/local/kong/nginx-kong.conf:73  
         這是因為編譯的openresty的時候,沒有指定--with-http_realip_module,重新編譯安裝:
./configure --with-pcre-jit --with-http_ssl_module --with-http_realip_module --with-http_stub_status_module --with-http_v2_module make -j2 make install //默認安裝在/usr/local/bin/openresty export PATH=/usr/local/openresty/bin:$PATH 
         
