微服務入門:Openresty實現API網關

概念介紹
如果大家清楚“網關”這個概念,那就很容易理解“API網關“,即所有API的入口。 從面向對象設計的角度看,它與外觀模式類似,封裝了系統內部架構。在單體應用架構中,沒有「 API網關 」的概念,每個項目都會用到filter/過濾器之類的東西,filter的作用就是把項目中的一些非業務邏輯的功能抽離出來獨立處理,避免與業務邏輯混在一起增加代碼復雜度。比如 鑒權認證功能、Session處理、安全檢查、日志處理等等。
如果采用微服務架構,那一個項目中微服務節點很多,如果讓每一個節點都去處理上面這些 “鑒權認證功能、Session處理、安全檢查、日志處理等” 會多出很多冗余的代碼,也會給增加業務代碼的復雜度,因此就需要有一個API網關把這些公共的功能獨立出來成為一個服務來統一的處理這些事情。

主要功能
API網關就像是微服務的一扇門,是連通外部客戶端與內部微服務之間的一個橋梁。
其主要功能有:
- 路由轉發 API網關是內部微服務的對外唯一入口,所以外面全部的請求都會先發到API網上,然后由API網關來根據不同的請求去路由到不同的微服務節點上。
- 負載均衡 API網關收到外部請求之后,可以根據內部微服務每個實例的負荷情況進行動態的負載均衡調節。一旦內部的某個微服務實例負載很高,甚至是不能及時響應,則API網關就通過負載均衡策略減少或停止向這個實例轉發請求。當所有的內部微服務實例都處理不過來的時候,API網關還可以采用限流或熔斷的形式阻止外部請求,以保障整個系統的可用性。
- 安全認證 API網關就像是微服務的大門守衛,每一個請求進來之后,都必須先在API網關上進行安全驗證或身份驗證,驗證通過后才轉發給后面的服務。
- 日志記錄 所有的請求都需要走API網關,那么就可以在API網關上統一集中的記錄下這些行為日志。
- 數據轉換 因為API網關對外是面向多種不同的客戶端,不同的客戶端所傳輸的數據類型可能是不一樣的。因此API網關還需要具備數據轉換的功能,將不同客戶端傳輸進來的數據轉換成同一種類型再轉發給內部微服務上,這樣,兼容了這些請求的多樣性,保證了微服務的靈活性。
OpenResty
API網關最主要的功能實現就是請求攔截,在網絡請求的整個生命階段加入各種filter/過濾器, OpenResty提供了這樣的功能。
OpenResty® 是一個基于 Nginx 與 Lua 的高性能 Web 平臺,其內部集成了大量精良的 Lua 庫、第三方模塊以及大多數的依賴項。用于方便地搭建能夠處理超高并發、擴展性極高的動態 Web 應用、Web 服務和動態網關。
OpenResty 處理一個請求,它的處理流程請參考下圖(從 Request start 開始):

依據OpenResty的請求處理流程,和各種第三方模塊,就可以在流程節點中加入我們的API網關邏輯代碼。例如,對API請求數量進行統計:
- lua_package_path "module/lua-resty-hmac/lib/?.lua;module/lua-resty-redis/lib/?.lua;module/lua-resty-mysql/lib/?.lua;module/lua-resty-jwt/lib/?.lua;;";
- server {
- listen 80;
- server_name gw.gitlib.cn;
- access_log /var/log/nginx/gw.gitlib.cn.access.log access;
- # lua_code_cache off;
- set $redis_host "192.168.1.106";
- set $redis_port "6379";
- set $redis_incrkey "api:access:num";
- access_by_lua_file gateway/intercept.lua; # 對所有請求進行攔截處理
- location = /num {
- content_by_lua_block {
- local _redis = require "resty.redis"
- local redis = _redis:new()
- redis:set_timeout(1000)
- local ok, err = redis:connect(ngx.var.redis_host, ngx.var.redis_port)
- if not ok then
- ngx.say("failed to connect: ", err)
- return
- end
- local res, err = redis:get(ngx.var.redis_incrkey)
- if not res then
- ngx.say("failed to get key: ", err)
- return
- end
- if res == ngx.null then
- ngx.say("key not found.")
- return
- end
- ngx.say("api:access:num:", res)
- }
- }
- location ~ ^/api/([\w]+) {
- default_type text/html;
- content_by_lua_file /web/gw/api/$1.lua;
- }
- }
上面是我們的nginx配置,引入了redis模塊,用于存儲API請求數量,接下來,我們在gateway/intercept.lua中實現API請求數量統計的處理邏輯:
- local function increseNum(key)
- -- get key from rediskey
- local _redis = require "resty.redis"
- local redis = _redis:new()
- redis:set_timeout(100)
- local ok, err = redis:connect(ngx.var.redis_host, ngx.var.redis_port)
- if not ok then
- ngx.log(ngx.ERR, "failed to connect to redis: ", err)
- return nil
- end
- if ngx.var.redis_auth then
- local ok, err = redis:auth(ngx.var.redis_auth)
- if not ok then
- ngx.log(ngx.ERR, "failed to authenticate: ", err)
- return nil
- end
- end
- if ngx.var.redis_db then
- local ok, err = redis:select(ngx.var.redis_db)
- if not ok then
- ngx.log(ngx.ERR, "failed to select db: ", ngx.var.reddb, " ", err)
- return nil
- end
- end
- local res, err = redis:incr(key)
- if not res then
- ngx.log(ngx.ERR, "failed to incr key: ", key ,", ", err)
- return nil
- end
- if res == ngx.null then
- ngx.log(ngx.ERR, "key ", key, " not found")
- return ngx.null
- end
- local ok, err = redis:close()
- if not ok then
- ngx.log(ngx.ERR, "failed to close: ", err)
- end
- return res
- end
- increseNum(ngx.var.redis_incrkey)
就這樣,我們實現了API網關的一個小功能,其他功能實現,就靠大家去摸索了。目前市面上成熟的API網關實現方案有很多,采用openresty 開發出的api網關,比如比較流行的kong、orange等, 大家可以自行了解。