開源API網(wǎng)關(guān),到底哪個(gè)強(qiáng)?
本文主要分析了 Nginx、Kong、APISIX、Tyk、Zuul、Gravitee 幾個(gè)開源 API 網(wǎng)關(guān)架構(gòu)及基本功能,測試了一定場景下各個(gè) API 網(wǎng)關(guān)的性能,文末附有源碼地址。

圖片來自 Pexels
我今天就在和大家探討一下 API Gateway。在微服務(wù)的架構(gòu)下,API 網(wǎng)關(guān)是一個(gè)常見的架構(gòu)設(shè)計(jì)模式。

以下是微服務(wù)中常見的問題,需要引入 API 網(wǎng)關(guān)來協(xié)助解決:
微服務(wù)提供的 API 的粒度通常與客戶端所需的粒度不同。微服務(wù)通常提供細(xì)粒度的 API,這意味著客戶端需要與多個(gè)服務(wù)進(jìn)行交互。例如,如上所述,需要產(chǎn)品詳細(xì)信息的客戶需要從眾多服務(wù)中獲取數(shù)據(jù)。
不同的客戶端需要不同的數(shù)據(jù)。例如,產(chǎn)品詳細(xì)信息頁面桌面的桌面瀏覽器版本通常比移動版本更為詳盡。
對于不同類型的客戶端,網(wǎng)絡(luò)性能是不同的。例如,與非移動網(wǎng)絡(luò)相比,移動網(wǎng)絡(luò)通常要慢得多并且具有更高的延遲。而且,當(dāng)然,任何 WAN 都比 LAN 慢得多。
這意味著本機(jī)移動客戶端使用的網(wǎng)絡(luò)性能與服務(wù)器端 Web 應(yīng)用程序使用的 LAN 的性能差異很大。服務(wù)器端 Web 應(yīng)用程序可以向后端服務(wù)發(fā)出多個(gè)請求,而不會影響用戶體驗(yàn),而移動客戶端只能提供幾個(gè)請求。
微服務(wù)實(shí)例數(shù)量及其位置(主機(jī)+端口)動態(tài)變化。
服務(wù)劃分會隨著時(shí)間的推移而變化,應(yīng)該對客戶端隱藏。
服務(wù)可能會使用多種協(xié)議,其中一些協(xié)議可能對網(wǎng)絡(luò)不友好。
反向代理和路由:大多數(shù)項(xiàng)目采用網(wǎng)關(guān)的解決方案的最主要的原因。給出了訪問后端 API 的所有客戶端的單一入口,并隱藏內(nèi)部服務(wù)部署的細(xì)節(jié)。
負(fù)載均衡:網(wǎng)關(guān)可以將單個(gè)傳入的請求路由到多個(gè)后端目的地。
身份驗(yàn)證和授權(quán):網(wǎng)關(guān)應(yīng)該能夠成功進(jìn)行身份驗(yàn)證并僅允許可信客戶端訪問 API,并且還能夠使用類似 RBAC 等方式來授權(quán)。
IP 列表白名單/黑名單:允許或阻止某些 IP 地址通過。
性能分析:提供一種記錄與 API 調(diào)用相關(guān)的使用和其他有用度量的方法。
限速和流控:控制 API 調(diào)用的能力。
請求變形:在進(jìn)一步轉(zhuǎn)發(fā)之前,能夠在轉(zhuǎn)發(fā)之前轉(zhuǎn)換請求和響應(yīng)(包括 Header 和 Body)。
版本控制:同時(shí)使用不同版本的 API 選項(xiàng)或可能以金絲雀發(fā)布或藍(lán)/綠部署的形式提供慢速推出 API。
斷路器:微服務(wù)架構(gòu)模式有用,以避免使用中斷。
多協(xié)議支持:WebSocket/GRPC。
緩存:減少網(wǎng)絡(luò)帶寬和往返時(shí)間消耗,如果可以緩存頻繁要求的數(shù)據(jù),則可以提高性能和響應(yīng)時(shí)間
API 文檔:如果計(jì)劃將 API 暴露給組織以外的開發(fā)人員,那么必須考慮使用 API 文檔,例如 Swagger 或 OpenAPI。
API 使用了常見的寵物商店的樣例,聲明如下:
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
構(gòu)建好的 Web 服務(wù)通過 Docker Compose 來進(jìn)行容器化的部署。
version: "3.7"
services:
goapi:
container_name: goapi
image: naughtytao/goapi:0.1
ports:
- "18000:8080"
deploy:
resources:
limits:
cpus: '1'
memory: 256M
reservations:
memory: 256M
nodeapi:
container_name: nodeapi
image: naughtytao/nodeapi:0.1
ports:
- "18001:8080"
deploy:
resources:
limits:
cpus: '1'
memory: 256M
reservations:
memory: 256M
flaskapi:
container_name: flaskapi
image: naughtytao/flaskapi:0.1
ports:
- "18002:8080"
deploy:
resources:
limits:
cpus: '1'
memory: 256M
reservations:
memory: 256M
springapi:
container_name: springapi
image: naughtytao/springapi:0.1
ports:
- "18003:8080"
deploy:
resources:
limits:
cpus: '1'
memory: 256M
reservations:
memory: 256M
這里用戶發(fā)送的請求 server/service_name/v1/ 會發(fā)送給 API 網(wǎng)關(guān),網(wǎng)關(guān)通過 service name 來路由到不同的后端服務(wù)。

Nginx
由 C 編寫,占用的資源和內(nèi)存低,性能高。
單進(jìn)程多線程,當(dāng)啟動 Nginx 服務(wù)器,會生成一個(gè) master 進(jìn)程,master 進(jìn)程會 fork 出多個(gè) worker 進(jìn)程,由 worker 線程處理客戶端的請求。
支持反向代理,支持 7 層負(fù)載均衡(拓展負(fù)載均衡的好處)。
高并發(fā),Nginx 是異步非阻塞型處理請求,采用的 epollandqueue 模式。
處理靜態(tài)文件速度快。
高度模塊化,配置簡單。社區(qū)活躍,各種高性能模塊出品迅速。

為了實(shí)現(xiàn) API 的路由轉(zhuǎn)發(fā),需要只需要對 Nginx 作出如下的配置:
server {
listen 80 default_server;
location /goapi {
rewrite ^/goapi(.*) $1 break;
proxy_pass http://goapi:8080;
}
location /nodeapi {
rewrite ^/nodeapi(.*) $1 break;
proxy_pass http://nodeapi:8080;
}
location /flaskapi {
rewrite ^/flaskapi(.*) $1 break;
proxy_pass http://flaskapi:8080;
}
location /springapi {
rewrite ^/springapi(.*) $1 break;
proxy_pass http://springapi:8080;
}
}
Nginx 的部署如下:
version: "3.7"
services:
web:
container_name: nginx
image: nginx
volumes:
- ./templates:/etc/nginx/templates
- ./conf/default.conf:/etc/nginx/conf.d/default.conf
ports:
- "8080:80"
environment:
- NGINX_HOST=localhost
- NGINX_PORT=80
deploy:
resources:
limits:
cpus: '1'
memory: 256M
reservations:
memory: 256M

Kong
而 Kong 本身利用這些掛鉤來路由和轉(zhuǎn)換請求。數(shù)據(jù)庫支持 Cassandra 或 Postgres 存儲所有配置。

我們使用以下的配置部署 Kong 到容器中(省略四個(gè)微服務(wù)的部署):
version: '3.7'
volumes:
kong_data: {}
networks:
kong-net:
external: false
services:
kong:
image: "${KONG_DOCKER_TAG:-kong:latest}"
user: "${KONG_USER:-kong}"
depends_on:
- db
environment:
KONG_ADMIN_ACCESS_LOG: /dev/stdout
KONG_ADMIN_ERROR_LOG: /dev/stderr
KONG_ADMIN_LISTEN: '0.0.0.0:8001'
KONG_CASSANDRA_CONTACT_POINTS: db
KONG_DATABASE: postgres
KONG_PG_DATABASE: ${KONG_PG_DATABASE:-kong}
KONG_PG_HOST: db
KONG_PG_USER: ${KONG_PG_USER:-kong}
KONG_PROXY_ACCESS_LOG: /dev/stdout
KONG_PROXY_ERROR_LOG: /dev/stderr
KONG_PG_PASSWORD_FILE: /run/secrets/kong_postgres_password
secrets:
- kong_postgres_password
networks:
- kong-net
ports:
- "8080:8000/tcp"
- "127.0.0.1:8001:8001/tcp"
- "8443:8443/tcp"
- "127.0.0.1:8444:8444/tcp"
healthcheck:
test: ["CMD", "kong", "health"]
interval: 10s
timeout: 10s
retries: 10
restart: on-failure
deploy:
restart_policy:
condition: on-failure
db:
image: postgres:9.5
environment:
POSTGRES_DB: ${KONG_PG_DATABASE:-kong}
POSTGRES_USER: ${KONG_PG_USER:-kong}
POSTGRES_PASSWORD_FILE: /run/secrets/kong_postgres_password
secrets:
- kong_postgres_password
healthcheck:
test: ["CMD", "pg_isready", "-U", "${KONG_PG_USER:-kong}"]
interval: 30s
timeout: 30s
retries: 3
restart: on-failure
deploy:
restart_policy:
condition: on-failure
stdin_open: true
tty: true
networks:
- kong-net
volumes:
- kong_data:/var/lib/postgresql/data
secrets:
kong_postgres_password:
file: ./POSTGRES_PASSWORD
數(shù)據(jù)庫選擇了 PostgreSQL,開源版本沒有 Dashboard,我們使用 RestAPI 創(chuàng)建所有的網(wǎng)關(guān)路由:
curl -i -X POST http://localhost:8001/services \
--data name=goapi \
--data url='http://goapi:8080'
curl -i -X POST http://localhost:8001/services/goapi/routes \
--data 'paths[]=/goapi' \
--data name=goapi
使用 K6 壓力測試的結(jié)果如下:

APISIX
云原生設(shè)計(jì),輕巧且易于容器化。
集成了統(tǒng)計(jì)和監(jiān)視組件,例如 Prometheus,Apache Skywalking 和 Zipkin。
支持 gRPC,Dubbo,WebSocket,MQTT 等代理協(xié)議,以及從 HTTP 到 gRPC 的協(xié)議轉(zhuǎn)碼,以適應(yīng)各種情況。
擔(dān)當(dāng) OpenID 依賴方的角色,與 Auth0,Okta 和其他身份驗(yàn)證提供程序的服務(wù)連接。
通過在運(yùn)行時(shí)動態(tài)執(zhí)行用戶功能來支持無服務(wù)器,從而使網(wǎng)關(guān)的邊緣節(jié)點(diǎn)更加靈活。
支持插件熱加載。
不鎖定用戶,支持混合云部署架構(gòu)。
網(wǎng)關(guān)節(jié)點(diǎn)無狀態(tài),可以靈活擴(kuò)展。
APISIX 的架構(gòu)如下圖所示:

我們同樣使用 Docker Compose 來部署 APISIX:
version: "3.7"
services:
apisix-dashboard:
image: apache/apisix-dashboard:2.4
restart: always
volumes:
- ./dashboard_conf/conf.yaml:/usr/local/apisix-dashboard/conf/conf.yaml
ports:
- "9000:9000"
networks:
apisix:
ipv4_address: 172.18.5.18
apisix:
image: apache/apisix:2.3-alpine
restart: always
volumes:
- ./apisix_log:/usr/local/apisix/logs
- ./apisix_conf/config.yaml:/usr/local/apisix/conf/config.yaml:ro
depends_on:
- etcd
##network_mode: host
ports:
- "8080:9080/tcp"
- "9443:9443/tcp"
networks:
apisix:
ipv4_address: 172.18.5.11
deploy:
resources:
limits:
cpus: '1'
memory: 256M
reservations:
memory: 256M
etcd:
image: bitnami/etcd:3.4.9
user: root
restart: always
volumes:
- ./etcd_data:/etcd_data
environment:
ETCD_DATA_DIR: /etcd_data
ETCD_ENABLE_V2: "true"
ALLOW_NONE_AUTHENTICATION: "yes"
ETCD_ADVERTISE_CLIENT_URLS: "http://0.0.0.0:2379"
ETCD_LISTEN_CLIENT_URLS: "http://0.0.0.0:2379"
ports:
- "2379:2379/tcp"
networks:
apisix:
ipv4_address: 172.18.5.10
networks:
apisix:
driver: bridge
ipam:
config:
- subnet: 172.18.0.0/16
創(chuàng)建一個(gè)服務(wù)的路由的命令如下:
curl --location --request PUT 'http://127.0.0.1:8080/apisix/admin/routes/1' \
--header 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' \
--header 'Content-Type: text/plain' \
--data-raw '{
"uri": "/goapi/*",
"plugins": {
"proxy-rewrite": {
"regex_uri": ["^/goapi(.*)$","$1"]
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"goapi:8080": 1
}
}
}'
使用 K6 壓力測試的結(jié)果如下:

Tyk
Tyk 支持不同的運(yùn)行方式:云,混合(在自己的基礎(chǔ)架構(gòu)中為 GW)和本地。

網(wǎng)關(guān):處理所有應(yīng)用流量的代理。
儀表板:可以從中管理 Tyk,顯示指標(biāo)和組織 API 的界面。
Pump:負(fù)責(zé)持久保存指標(biāo)數(shù)據(jù),并將其導(dǎo)出到 MongoDB(內(nèi)置),ElasticSearch 或 InfluxDB 等。
我們同樣使用 Docker Compose 來創(chuàng)建 Tyk 網(wǎng)關(guān)來進(jìn)行功能驗(yàn)證。
version: '3.7'
services:
tyk-gateway:
image: tykio/tyk-gateway:v3.1.1
ports:
- 8080:8080
volumes:
- ./tyk.standalone.conf:/opt/tyk-gateway/tyk.conf
- ./apps:/opt/tyk-gateway/apps
- ./middleware:/opt/tyk-gateway/middleware
- ./certs:/opt/tyk-gateway/certs
environment:
- TYK_GW_SECRET=foo
depends_on:
- tyk-redis
tyk-redis:
image: redis:5.0-alpine
ports:
- 6379:6379
curl --location --request POST 'http://localhost:8080/tyk/apis/' \
--header 'x-tyk-authorization: foo' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "GO API",
"slug": "go-api",
"api_id": "goapi",
"org_id": "goapi",
"use_keyless": true,
"auth": {
"auth_header_name": "Authorization"
},
"definition": {
"location": "header",
"key": "x-api-version"
},
"version_data": {
"not_versioned": true,
"versions": {
"Default": {
"name": "Default",
"use_extended_paths": true
}
}
},
"proxy": {
"listen_path": "/goapi/",
"target_url": "http://host.docker.internal:18000/",
"strip_listen_path": true
},
"active": true
}'
使用 K6 壓力測試的結(jié)果如下:

Zuul
Zuul 是 Netflix 開源的基于 Java 的 API 網(wǎng)關(guān)組件。

zuul-core:該庫包含編譯和執(zhí)行過濾器的核心功能。
zuul-simple-webapp:該 Webapp 展示了一個(gè)簡單的示例,說明如何使用 zuul-core 構(gòu)建應(yīng)用程序。
zuul-netflix:將其他 NetflixOSS 組件添加到 Zuul 的庫,例如,使用 Ribbon 路由請求。
zuul-netflix-webapp:將 zuul-core 和 zuul-netflix 打包到一個(gè)易于使用的程序包中的 webapp。
Hystrix 用于流控。包裝對始發(fā)地的呼叫,這使我們可以在發(fā)生問題時(shí)丟棄流量并確定流量的優(yōu)先級。
Ribbon 是來自 Zuul 的所有出站請求的客戶,它提供有關(guān)網(wǎng)絡(luò)性能和錯(cuò)誤的詳細(xì)信息,并處理軟件負(fù)載平衡以實(shí)現(xiàn)均勻的負(fù)載分配。
Turbine 實(shí)時(shí)匯總細(xì)粒度的指標(biāo),以便我們可以快速觀察問題并做出反應(yīng)。
Archaius 處理配置并提供動態(tài)更改屬性的能力。
類型:通常定義路由流程中應(yīng)用過濾器的階段。(盡管它可以是任何自定義字符串)
執(zhí)行順序:在類型中應(yīng)用,定義跨多個(gè)過濾器的執(zhí)行順序。
準(zhǔn)則:執(zhí)行過濾器所需的條件。
動作:如果符合條件,則要執(zhí)行的動作。
class DeviceDelayFilter extends ZuulFilter {
def static Random rand = new Random()
@Override
String filterType() {
return 'pre'
}
@Override
int filterOrder() {
return 5
}
@Override
boolean shouldFilter() {
return RequestContext.getRequest().
getParameter("deviceType")?equals("BrokenDevice"):false
}
@Override
Object run() {
sleep(rand.nextInt(20000)) // Sleep for a random number of
// seconds between [0-20]
}
}
而是通過每個(gè)請求唯一的 RequestContext 共享狀態(tài)。過濾器使用 Groovy 編寫。

Pre 過濾器在路由到原點(diǎn)之前執(zhí)行。示例包括請求身份驗(yàn)證,選擇原始服務(wù)器以及記錄調(diào)試信息。
Route 路由過濾器處理將請求路由到源。這是使用 Apache HttpClient 或 Netflix Ribbon 構(gòu)建和發(fā)送原始 HTTP 請求的地方。
在將請求路由到源之后,將執(zhí)行 Post 過濾器。示例包括將標(biāo)準(zhǔn) HTTP 標(biāo)頭添加到響應(yīng),收集統(tǒng)計(jì)信息和指標(biāo)以及將響應(yīng)從源流傳輸?shù)娇蛻舳恕?/span>
在其他階段之一發(fā)生錯(cuò)誤時(shí),將執(zhí)行 Error 過濾器。
對應(yīng)的 Java 的 POM 如下:
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>naughtytao.apigateway</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.7.RELEASE</version>
<relativePath />
<!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- Dependencies -->
<spring-cloud.version>Camden.SR7</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- enable authentication if security is included -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
</dependency>
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.0.0-M5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
主要應(yīng)用代碼如下:
package naughtytao.apigateway.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Bean;
import naughtytao.apigateway.demo.filters.ErrorFilter;
import naughtytao.apigateway.demo.filters.PostFilter;
import naughtytao.apigateway.demo.filters.PreFilter;
import naughtytao.apigateway.demo.filters.RouteFilter;
@SpringBootApplication
@EnableAutoConfiguration(exclude = { RabbitAutoConfiguration.class })
@EnableZuulProxy
@ComponentScan("naughtytao.apigateway.demo")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Docker 構(gòu)建文件如下:
FROM maven:3.6.3-openjdk-11
WORKDIR /usr/src/app
COPY src ./src
COPY pom.xml ./
RUN mvn -f ./pom.xml clean package -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/src/app/target/demo-0.0.1-SNAPSHOT.jar"]
路由的配置寫在 application.properties 中:
#Zuul routes.
zuul.routes.goapi.url=http://goapi:8080
zuul.routes.nodeapi.url=http://nodeapi:8080
zuul.routes.flaskapi.url=http://flaskapi:8080
zuul.routes.springapi.url=http://springapi:8080
ribbon.eureka.enabled=false
server.port=8080
我們同樣使用 Docker Compose 運(yùn)行 Zuul 的網(wǎng)關(guān)來進(jìn)行驗(yàn)證:
version: '3.7'
services:
gateway:
image: naughtytao/zuulgateway:0.1
ports:
- 8080:8080
volumes:
- ./config/application.properties:/usr/src/app/config/application.properties
deploy:
resources:
limits:
cpus: '1'
memory: 256M
reservations:
memory: 256M
使用 K6 壓力測試的結(jié)果如下:

在相同的配置條件下(單核,256M),Zuul 的壓測結(jié)果要明顯差于其它幾個(gè),只有 200 左右。

Gravitee
Gravitee 是 Gravitee.io 開源的,基于 Java 的,簡單易用,性能高,且具成本效益的開源 API 平臺,可幫助組織保護(hù),發(fā)布和分析您的 API。

Gravitee 可以通過設(shè)計(jì)工作室和路徑的兩種方式來創(chuàng)建和管理 API:

Gravity 提供網(wǎng)關(guān),API 門戶和 API 管理,其中網(wǎng)關(guān)和管理 API 部分是開源的,門戶需要注冊許可證來使用。


我們同樣使用 Docker Compose 來部署整個(gè) Gravitee 的棧:
#
# Copyright (C) 2015 The Gravitee team (http://gravitee.io)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
version: '3.7'
networks:
frontend:
name: frontend
storage:
name: storage
volumes:
data-elasticsearch:
data-mongo:
services:
mongodb:
image: mongo:${MONGODB_VERSION:-3.6}
container_name: gio_apim_mongodb
restart: always
volumes:
- data-mongo:/data/db
- ./logs/apim-mongodb:/var/log/mongodb
networks:
- storage
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:${ELASTIC_VERSION:-7.7.0}
container_name: gio_apim_elasticsearch
restart: always
volumes:
- data-elasticsearch:/usr/share/elasticsearch/data
environment:
- http.host=0.0.0.0
- transport.host=0.0.0.0
- xpack.security.enabled=false
- xpack.monitoring.enabled=false
- cluster.name=elasticsearch
- bootstrap.memory_lock=true
- discovery.type=single-node
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
ulimits:
memlock:
soft: -1
hard: -1
nofile: 65536
networks:
- storage
gateway:
image: graviteeio/apim-gateway:${APIM_VERSION:-3}
container_name: gio_apim_gateway
restart: always
ports:
- "8082:8082"
depends_on:
- mongodb
- elasticsearch
volumes:
- ./logs/apim-gateway:/opt/graviteeio-gateway/logs
environment:
- gravitee_management_mongodb_uri=mongodb://mongodb:27017/gravitee?serverSelectionTimeoutMS=5000&connectTimeoutMS=5000&socketTimeoutMS=5000
- gravitee_ratelimit_mongodb_uri=mongodb://mongodb:27017/gravitee?serverSelectionTimeoutMS=5000&connectTimeoutMS=5000&socketTimeoutMS=5000
- gravitee_reporters_elasticsearch_endpoints_0=http://elasticsearch:9200
networks:
- storage
- frontend
deploy:
resources:
limits:
cpus: '1'
memory: 256M
reservations:
memory: 256M
management_api:
image: graviteeio/apim-management-api:${APIM_VERSION:-3}
container_name: gio_apim_management_api
restart: always
ports:
- "8083:8083"
links:
- mongodb
- elasticsearch
depends_on:
- mongodb
- elasticsearch
volumes:
- ./logs/apim-management-api:/opt/graviteeio-management-api/logs
environment:
- gravitee_management_mongodb_uri=mongodb://mongodb:27017/gravitee?serverSelectionTimeoutMS=5000&connectTimeoutMS=5000&socketTimeoutMS=5000
- gravitee_analytics_elasticsearch_endpoints_0=http://elasticsearch:9200
networks:
- storage
- frontend
management_ui:
image: graviteeio/apim-management-ui:${APIM_VERSION:-3}
container_name: gio_apim_management_ui
restart: always
ports:
- "8084:8080"
depends_on:
- management_api
environment:
- MGMT_API_URL=http://localhost:8083/management/organizations/DEFAULT/environments/DEFAULT/
volumes:
- ./logs/apim-management-ui:/var/log/nginx
networks:
- frontend
portal_ui:
image: graviteeio/apim-portal-ui:${APIM_VERSION:-3}
container_name: gio_apim_portal_ui
restart: always
ports:
- "8085:8080"
depends_on:
- management_api
environment:
- PORTAL_API_URL=http://localhost:8083/portal/environments/DEFAULT
volumes:
- ./logs/apim-portal-ui:/var/log/nginx
networks:
- frontend
我們使用管理 UI 來創(chuàng)建四個(gè)對應(yīng)的 API 來進(jìn)行網(wǎng)關(guān)的路由,也可以用 API 的方式,Gravitee 是這個(gè)開源網(wǎng)關(guān)中,唯一管理 UI 也開源的產(chǎn)品。

使用 K6 壓力測試的結(jié)果如下:

和同樣采用 Java 的 Zuul 類似,Gravitee 的響應(yīng)只能達(dá)到 200 左右,而且還出現(xiàn)了一些錯(cuò)誤。我們只好再一次提高網(wǎng)關(guān)的資源分配到 4 核 2G。

總結(jié)
https://github.com/gangtao/api-gateway
作者:Gang Tao
編輯:陶家龍
出處:zhuanlan.zhihu.com/p/358862217


長鏈接轉(zhuǎn)短鏈的那些難事?。?!

程序員的媽媽居然是產(chǎn)品經(jīng)理,她會如何逼你結(jié)婚?

