内容大纲
- 1. API网关概述
- 2. Kong API网关
- 3. AWS API Gateway
- 4. Azure API Management
- 5. Spring Cloud Gateway
- 6. Nginx API网关
- 7. API网关功能
- 8. 安全管理
- 9. 监控与分析
- 10. 最佳实践
1. API网关概述
API网关是微服务架构中的重要组件,它作为系统的统一入口,负责请求路由、协议转换、身份认证、限流熔断等功能。API网关可以简化客户端与微服务之间的通信,提高系统的安全性和可维护性。
API网关的核心功能包括:
- 请求路由和负载均衡
- 身份认证和授权
- 限流和熔断
- 协议转换
- 请求和响应转换
- 监控和日志
- API版本管理
- 缓存
学习交流加群风哥微信: itpux-com
2. Kong API网关
2.1 Kong安装
# 使用Docker安装Kong
# 创建Kong网络
$ docker network create kong-net
# 启动PostgreSQL数据库
$ docker run -d –name kong-database \
–network=kong-net \
-p 5432:5432 \
-e “POSTGRES_USER=kong” \
-e “POSTGRES_DB=kong” \
-e “POSTGRES_PASSWORD=kong” \
postgres:9.6
# 初始化Kong数据库
$ docker run –rm \
–network=kong-net \
-e “KONG_DATABASE=postgres” \
-e “KONG_PG_HOST=kong-database” \
-e “KONG_PG_PASSWORD=kong” \
-e “KONG_CASSANDRA_CONTACT_POINTS=kong-database” \
kong:latest kong migrations bootstrap
# 启动Kong
$ docker run -d –name kong \
–network=kong-net \
-e “KONG_DATABASE=postgres” \
-e “KONG_PG_HOST=kong-database” \
-e “KONG_PG_PASSWORD=kong” \
-e “KONG_PROXY_ACCESS_LOG=/dev/stdout” \
-e “KONG_ADMIN_ACCESS_LOG=/dev/stdout” \
-e “KONG_PROXY_ERROR_LOG=/dev/stderr” \
-e “KONG_ADMIN_ERROR_LOG=/dev/stderr” \
-e “KONG_ADMIN_LISTEN=0.0.0.0:8001, 0.0.0.0:8444 ssl” \
-p 8000:8000 \
-p 8443:8443 \
-p 8001:8001 \
-p 8444:8444 \
kong:latest
# 验证Kong安装
$ curl -i http://fgedudb:8001/
# 输出结果
HTTP/1.1 200 OK
Date: Fri, 03 Apr 2026 10:00:00 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/2.8.0
Content-Length: 12345
{
“plugins”: {
“enabled_in_cluster”: […],
“available_on_server”: […]
},
“tagline”: “Welcome to kong”,
“configuration”: {…},
“version”: “2.8.0”,
“node_id”: “abc123-def456-ghi789”,
“lua_version”: “LuaJIT 2.1.0-beta3”,
“hostname”: “kong”
}
2.2 Kong配置
# 添加服务
$ curl -X POST http://fgedudb:8001/services \
–data “name=user-service” \
–data “url=http://user-service:8080”
# 输出结果
{
“id”: “abc123-def456-ghi789”,
“created_at”: 1680500400,
“updated_at”: 1680500400,
“name”: “user-service”,
“protocol”: “http”,
“host”: “user-service”,
“port”: 8080,
“path”: null,
“retries”: 5,
“connect_timeout”: 60000,
“write_timeout”: 60000,
“read_timeout”: 60000
}
# 添加路由
$ curl -X POST http://fgedudb:8001/services/user-service/routes \
–data “paths[]=/api/users” \
–data “methods[]=GET” \
–data “methods[]=POST”
# 输出结果
{
“id”: “jkl012-mno345-pqr678”,
“created_at”: 1680500400,
“updated_at”: 1680500400,
“name”: null,
“protocols”: [“http”, “https”],
“methods”: [“GET”, “POST”],
“hosts”: null,
“paths”: [“/api/users”],
“regex_priority”: 0,
“strip_path”: true,
“service”: {
“id”: “abc123-def456-ghi789”
}
}
# 添加插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=rate-limiting” \
–data “config.minute=100” \
–data “config.policy=local”
# 输出结果
{
“id”: “stu901-vwx234-yza567”,
“created_at”: 1680500400,
“name”: “rate-limiting”,
“config”: {
“minute”: 100,
“policy”: “local”
},
“service”: {
“id”: “abc123-def456-ghi789”
}
}
# 测试API
$ curl http://fgedudb:8000/api/users
# 输出结果
[
{“id”: 1, “name”: “风哥1号”, “email”: “zhangsan@fgedu.net.cn”},
{“id”: 2, “name”: “风哥2号”, “email”: “lisi@fgedu.net.cn”}
]
风哥风哥提示:Kong是一个功能强大的API网关,支持插件扩展,可以满足各种复杂的业务需求。
3. AWS API Gateway
3.1 AWS API Gateway配置
# 创建REST API
$ aws apigateway create-rest-api \
–name ‘MyAPI’ \
–description ‘My REST API’
# 输出结果
{
“id”: “abc123def4”,
“name”: “MyAPI”,
“description”: “My REST API”,
“createdDate”: 1680500400,
“version”: “1.0”,
“apiKeySource”: “HEADER”
}
# 创建资源
$ aws apigateway create-resource \
–rest-api-id abc123def4 \
–parent-id xyz789abc0 \
–path-part users
# 输出结果
{
“id”: “def456ghi7”,
“parentId”: “xyz789abc0”,
“pathPart”: “users”,
“path”: “/users”
}
# 创建方法
$ aws apigateway put-method \
–rest-api-id abc123def4 \
–resource-id def456ghi7 \
–http-method GET \
–authorization-type NONE
# 设置集成
$ aws apigateway put-integration \
–rest-api-id abc123def4 \
–resource-id def456ghi7 \
–http-method GET \
–type HTTP_PROXY \
–integration-http-method GET \
–uri ‘http://user-service:8080/api/users’
# 部署API
$ aws apigateway create-deployment \
–rest-api-id abc123def4 \
–stage-name prod
# 输出结果
{
“id”: “ghi789jkl0”,
“createdDate”: 1680500400
}
# 测试API
$ curl https://abc123def4.execute-api.us-west-2.amazonaws.com/prod/users
# 输出结果
[
{“id”: 1, “name”: “风哥1号”, “email”: “zhangsan@fgedu.net.cn”},
{“id”: 2, “name”: “风哥2号”, “email”: “lisi@fgedu.net.cn”}
]
3.2 AWS API Gateway高级配置
# 创建使用计划
$ aws apigateway create-usage-plan \
–name ‘Basic Plan’ \
–description ‘Basic usage plan’ \
–throttle burstLimit=100,rateLimit=50 \
–quota limit=1000,offset=0,period=DAY
# 创建API密钥
$ aws apigateway create-api-key \
–name ‘MyAPIKey’ \
–description ‘My API Key’ \
–enabled
# 输出结果
{
“id”: “jkl012mno3”,
“value”: “abc123def456ghi789jkl012mno345”,
“name”: “MyAPIKey”,
“description”: “My API Key”,
“enabled”: true,
“createdDate”: 1680500400
}
# 创建授权器
$ aws apigateway create-authorizer \
–rest-api-id abc123def4 \
–name ‘MyAuthorizer’ \
–type TOKEN \
–authorizer-uri ‘arn:aws:lambda:us-west-2:123456789012:function:my-authorizer’ \
–identity-source ‘method.request.header.Authorization’
# 设置CORS
$ aws apigateway update-method \
–rest-api-id abc123def4 \
–resource-id def456ghi7 \
–http-method GET \
–patch-operations op=replace,path=/responseParameters/method.response.header.Access-Control-Allow-Origin,value=”‘*'”
# 启用缓存
$ aws apigateway update-stage \
–rest-api-id abc123def4 \
–stage-name prod \
–patch-operations op=replace,path=/cacheClusterEnabled,value=true op=replace,path=/cacheClusterSize,value=’0.5’
更多学习教程www.fgedu.net.cn
4. Azure API Management
4.1 Azure API Management配置
# 创建API Management服务
$ az apim create \
–name myapim \
–resource-group myResourceGroup \
–publisher-name fgedu \
–publisher-email admin@fgedu.net.cn \
–sku-name Developer \
–sku-capacity 1
# 输出结果
{
“id”: “/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Microsoft.ApiManagement/service/myapim”,
“name”: “myapim”,
“type”: “Microsoft.ApiManagement/service”,
“location”: “East US”,
“sku”: {
“name”: “Developer”,
“capacity”: 1
},
“publisherEmail”: “admin@fgedu.net.cn”,
“publisherName”: “fgedu”
}
# 添加API
$ az apim api create \
–service-name myapim \
–resource-group myResourceGroup \
–api-id user-api \
–path /users \
–display-name “User API” \
–service-url “http://user-service:8080/api/users”
# 添加操作
$ az apim api operation create \
–service-name myapim \
–resource-group myResourceGroup \
–api-id user-api \
–operation-id get-users \
–method GET \
–url-template / \
–display-name “Get Users”
# 添加策略
$ az apim api policy create \
–service-name myapim \
–resource-group myResourceGroup \
–api-id user-api \
–xml-policy ‘
# 测试API
$ curl https://myapim.azure-api.net/users \
-H “Ocp-Apim-Subscription-Key: abc123def456ghi789”
# 输出结果
[
{“id”: 1, “name”: “风哥1号”, “email”: “zhangsan@fgedu.net.cn”},
{“id”: 2, “name”: “风哥2号”, “email”: “lisi@fgedu.net.cn”}
]
author:www.itpux.com
5. Spring Cloud Gateway
5.1 Spring Cloud Gateway配置
// application.yml
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
– id: user-service
uri: lb://user-service
predicates:
– Path=/api/users/**
filters:
– StripPrefix=1
– name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
key-resolver: “#{@userKeyResolver}”
– id: order-service
uri: lb://order-service
predicates:
– Path=/api/orders/**
filters:
– StripPrefix=1
– name: CircuitBreaker
args:
name: orderCircuitBreaker
fallbackUri: forward:/fallback
eureka:
client:
service-url:
defaultZone: http://fgedudb:8761/eureka/
// 自定义过滤器
@Component
public class AuthFilter implements GlobalFilter, Ordered {
@Override
public Mono
ServerHttpRequest request = exchange.getRequest();
String token = request.getHeaders().getFirst(“Authorization”);
if (token == null || !validateToken(token)) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return -100;
}
private boolean validateToken(String token) {
// 验证token逻辑
return true;
}
}
// 限流配置
@Configuration
public class RateLimiterConfig {
@Bean
public KeyResolver userKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}
}
// 启动类
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
// 测试API
$ curl http://fgedudb:8080/api/users
// 输出结果
[
{“id”: 1, “name”: “风哥1号”, “email”: “zhangsan@fgedu.net.cn”},
{“id”: 2, “name”: “风哥2号”, “email”: “lisi@fgedu.net.cn”}
]
更多学习教程公众号风哥教程itpux_com
6. Nginx API网关
6.1 Nginx配置
# nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 10240;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main ‘$remote_addr – $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for”‘;
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# 限流配置
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
# 上游服务器配置
upstream user_service {
server user-service-1:8080 weight=3;
server user-service-2:8080 weight=2;
server user-service-3:8080 weight=1;
keepalive 32;
}
upstream order_service {
server order-service-1:8080;
server order-service-2:8080;
keepalive 32;
}
# API网关配置
server {
listen 80;
server_name api.fgedu.net.cn;
# 用户服务
location /api/users {
limit_req zone=api_limit burst=20 nodelay;
limit_conn conn_limit 10;
proxy_pass http://user_service;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 超时配置
proxy_connect_timeout 30s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 熔断配置
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 30s;
}
# 订单服务
location /api/orders {
limit_req zone=api_limit burst=20 nodelay;
limit_conn conn_limit 10;
proxy_pass http://order_service;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 健康检查
location /health {
access_log off;
return 200 “OK\n”;
add_header Content-Type text/plain;
}
}
}
# 测试配置
$ nginx -t
# 输出结果
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# 重启Nginx
$ nginx -s reload
# 测试API
$ curl http://api.fgedu.net.cn/api/users
# 输出结果
[
{“id”: 1, “name”: “风哥1号”, “email”: “zhangsan@fgedu.net.cn”},
{“id”: 2, “name”: “风哥2号”, “email”: “lisi@fgedu.net.cn”}
]
风哥风哥提示:Nginx是一个高性能的Web服务器和反向代理,可以作为API网关使用,支持负载均衡、限流、缓存等功能。
7. API网关功能
7.1 请求路由
# 基于路径的路由
location /api/users {
proxy_pass http://user_service;
}
location /api/orders {
proxy_pass http://order_service;
}
# 基于域名的路由
server {
server_name user.api.fgedu.net.cn;
location / {
proxy_pass http://user_service;
}
}
server {
server_name order.api.fgedu.net.cn;
location / {
proxy_pass http://order_service;
}
}
# 基于请求头的路由
map $http_x_Service_Type $backend {
default user_service;
order order_service;
product product_service;
}
server {
location /api {
proxy_pass http://$backend;
}
}
# 基于请求参数的路由
location /api {
if ($arg_service = “order”) {
proxy_pass http://order_service;
}
if ($arg_service = “user”) {
proxy_pass http://user_service;
}
proxy_pass http://user_service;
}
7.2 限流熔断
# 限流配置
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location /api {
# 限流
limit_req zone=api_limit burst=20 nodelay;
limit_conn conn_limit 10;
# 熔断
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 30s;
proxy_pass http://backend;
}
}
# Kong限流插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=rate-limiting” \
–data “config.minute=100” \
–data “config.policy=local”
# Kong熔断插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=request-termination” \
–data “config.status_code=503” \
–data “config.message=Service temporarily unavailable”
学习交流加群风哥QQ113257174
8. 安全管理
8.1 身份认证
# Kong JWT认证插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=jwt”
# 创建消费者
$ curl -X POST http://fgedudb:8001/consumers \
–data “username=user1”
# 创建JWT凭证
$ curl -X POST http://fgedudb:8001/consumers/user1/jwt \
–data “key=abc123” \
–data “secret=xyz789”
# 测试JWT认证
$ curl http://fgedudb:8000/api/users \
-H “Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhYmMxMjMifQ.signature”
# Kong OAuth2认证插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=oauth2” \
–data “config.scopes=email,profile” \
–data “config.mandatory_scope=true”
# 创建OAuth2凭证
$ curl -X POST http://fgedudb:8001/consumers/user1/oauth2 \
–data “name=MyApp” \
–data “redirect_uris=http://fgedu.net.cn/callback”
# 输出结果
{
“client_id”: “abc123def456ghi789”,
“client_secret”: “jkl012mno345pqr678”,
“redirect_uris”: [“http://fgedu.net.cn/callback”]
}
8.2 访问控制
# Kong IP限制插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=ip-restriction” \
–data “config.allow=192.168.1.0/24”
# Kong ACL插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=acl” \
–data “config.allow=admin_group”
# 创建ACL组
$ curl -X POST http://fgedudb:8001/consumers/user1/acls \
–data “group=admin_group”
# Kong Bot检测插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=bot-detection”
# Nginx访问控制
location /api/admin {
allow 192.168.1.0/24;
deny all;
proxy_pass http://admin_service;
}
# 基于HTTP基本认证
location /api/secure {
auth_basic “Restricted Area”;
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend;
}
9. 监控与分析
9.1 监控配置
# Kong Prometheus插件
$ curl -X POST http://fgedudb:8001/plugins \
–data “name=prometheus”
# 访问指标
$ curl http://fgedudb:8001/metrics
# 输出结果
# HELP kong_http_status HTTP status codes per service/route in Kong
# TYPE kong_http_status counter
kong_http_status{service=”user-service”,route=”user-route”,code=”200″} 1234
kong_http_status{service=”user-service”,route=”user-route”,code=”404″} 56
kong_http_status{service=”order-service”,route=”order-route”,code=”200″} 789
# HELP kong_latency Latency added by Kong
# TYPE kong_latency histogram
kong_latency{service=”user-service”,le=”1″} 100
kong_latency{service=”user-service”,le=”5″} 500
kong_latency{service=”user-service”,le=”10″} 800
# Nginx监控配置
log_format json_combined escape=json ‘{‘
‘”time_local”:”$time_local”,’
‘”remote_addr”:”$remote_addr”,’
‘”remote_user”:”$remote_user”,’
‘”request”:”$request”,’
‘”status”:”$status”,’
‘”body_bytes_sent”:”$body_bytes_sent”,’
‘”request_time”:”$request_time”,’
‘”http_referrer”:”$http_referer”,’
‘”http_user_agent”:”$http_user_agent”‘
‘}’;
access_log /var/log/nginx/access.log json_combined;
# 配置Prometheus抓取
$ cat > prometheus.yml << EOF
scrape_configs:
- job_name: 'kong'
static_configs:
- targets: ['fgedudb:8001']
metrics_path: /metrics
EOF
9.2 日志分析
# Kong日志插件
$ curl -X POST http://fgedudb:8001/services/user-service/plugins \
–data “name=file-log” \
–data “config.path=/var/log/kong/user-service.log”
# ELK日志收集
$ cat > logstash.conf << EOF
input {
file {
path => “/var/log/nginx/access.log”
codec => json
start_position => “beginning”
}
}
filter {
grok {
match => { “message” => “%{COMBINEDAPACHELOG}” }
}
date {
match => [ “timestamp” , “dd/MMM/yyyy:HH:mm:ss Z” ]
}
}
output {
elasticsearch {
hosts => [“fgedudb:9200”]
index => “nginx-access-%{+YYYY.MM.dd}”
}
}
EOF
# Kibana查询示例
status:200 AND request:”GET /api/users”
status:[400 TO 499]
request_time:>1
10. 最佳实践
10.1 API网关最佳实践
- 选择合适的API网关实现
- 合理规划路由规则
- 配置安全策略
- 实施限流和熔断
- 建立完善的监控体系
- 定期备份配置
- 实施灰度发布
- 建立文档和知识库
10.2 安全最佳实践
- 启用身份认证
- 配置访问控制
- 使用HTTPS加密
- 定期审计访问日志
- 实施API密钥管理
10.3 性能最佳实践
- 配置合理的缓存策略
- 实施限流和熔断
- 优化连接池配置
- 使用异步处理
- 监控性能指标
- 选择合适的API网关实现
- 合理规划路由规则
- 配置安全策略
- 实施限流和熔断
- 建立完善的监控体系
- 定期备份配置
- 实施灰度发布
- 建立文档和知识库
author:www.itpux.com
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
