1. 首页 > IT综合教程 > 正文

IT教程FG401-API网关

内容大纲

1. API网关概述

API网关是一个位于客户端和后端服务之间的中间层,用于管理、路由和保护API请求。它提供了统一的入口点,简化了客户端与后端服务的交互,并提供了诸如认证、授权、限流、监控等功能。

API网关的核心功能包括:

  • 请求路由和负载均衡
  • 认证和授权
  • 限流和熔断
  • 监控和日志
  • 协议转换
  • 缓存
  • API版本管理

学习交流加群风哥微信: itpux-com

2. Kong API网关

2.1 Kong 简介

Kong是一个基于Nginx的开源API网关,它提供了丰富的插件生态系统,可以轻松扩展其功能。

2.2 Kong 安装

# 使用Docker安装Kong
$ docker network create kong-net

# 启动PostgreSQL
$ docker run -d –name kong-database \
–network=kong-net \
-p 5432:5432 \
-e POSTGRES_DB=kong \
-e POSTGRES_USER=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_CASSANDRA_CONTACT_POINTS=kong-database \
-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

5f7a4a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f
3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b
1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d

2.3 Kong 配置

# 创建服务
$ curl -X POST http://fgedudb:8001/services \
–data “name=example-service” \
–data “url=http://httpbin.org”

# 创建路由
$ curl -X POST http://fgedudb:8001/services/example-service/routes \
–data “paths[]=/example” \
–data “methods[]=GET”

# 测试API
$ curl -i http://fgedudb:8000/example/get

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 314
Connection: keep-alive
Date: Sat, 03 Apr 2026 00:00:00 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Server: gunicorn/19.9.0
Kong-Request-Id: 1234567890abcdef1234567890abcdef
X-Kong-Upstream-Latency: 100
X-Kong-Proxy-Latency: 10
Via: kong/2.6.0

{
“args”: {},
“headers”: {
“Accept”: “*/*”,
“Host”: “httpbin.org”,
“User-Agent”: “curl/7.64.1”,
“X-Forwarded-Host”: “fgedudb”
},
“origin”: “172.17.0.1, 1.2.3.4”,
“url”: “http://httpbin.org/get”
}

风哥风哥提示:Kong的插件生态系统非常丰富,可以通过添加不同的插件来扩展其功能,如认证、限流、监控等。

3. AWS API Gateway

3.1 AWS API Gateway 简介

AWS API Gateway是Amazon Web Services提供的托管API网关服务,它可以帮助开发者创建、发布、维护、监控和保护API。

3.2 AWS API Gateway 配置

# 使用AWS CLI创建API
$ aws apigateway create-rest-api –name “Example API”

# 创建资源
$ aws apigateway create-resource \
–rest-api-id \
–parent-id \
–path-part “example”

# 创建方法
$ aws apigateway put-method \
–rest-api-id \
–resource-id \
–http-method GET \
–authorization-type “NONE”

# 设置集成
$ aws apigateway put-integration \
–rest-api-id \
–resource-id \
–http-method GET \
–type HTTP \
–integration-http-method GET \
–uri “http://httpbin.org/get”

# 部署API
$ aws apigateway create-deployment \
–rest-api-id \
–stage-name prod

3.3 AWS API Gateway 监控

AWS API Gateway集成了CloudWatch,可以监控API的调用次数、错误率、延迟等指标。

更多学习教程www.fgedu.net.cn

4. Azure API Management

4.1 Azure API Management 简介

Azure API Management是Microsoft Azure提供的托管API网关服务,它可以帮助开发者创建、发布、维护、监控和保护API。

4.2 Azure API Management 配置

# 使用Azure CLI创建API Management服务
$ az apim create \
–name “example-apim” \
–resource-group “myResourceGroup” \
–location “West US” \
–publisher-name “Example Company” \
–publisher-email “contact@fgedu.net.cn”

# 导入API
$ az apim api import \
–name “example-api” \
–resource-group “myResourceGroup” \
–service-name “example-apim” \
–specification-url “https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml” \
–path “example”

# 发布API
$ az apim api release create \
–api-id “example-api” \
–resource-group “myResourceGroup” \
–service-name “example-apim” \
–release-id “release-1” \
–notes “Initial release”

5. Google API Gateway

5.1 Google API Gateway 简介

Google API Gateway是Google Cloud提供的托管API网关服务,它可以帮助开发者创建、发布、维护、监控和保护API。

5.2 Google API Gateway 配置

# 创建API配置
$ gcloud api-gateway api-configs create “example-api-config” \
–api=”example-api” \
–openapi-spec=”openapi.yaml” \
–project=”my-project”

# 创建API网关
$ gcloud api-gateway gateways create “example-gateway” \
–api=”example-api” \
–api-config=”example-api-config” \
–location=”us-central1″ \
–project=”my-project”

author:www.itpux.com

6. Spring Cloud Gateway

6.1 Spring Cloud Gateway 简介

Spring Cloud Gateway是Spring Cloud提供的API网关实现,它基于Spring Boot和Spring WebFlux,提供了丰富的路由和过滤功能。

6.2 Spring Cloud Gateway 配置

# application.yml
spring:
cloud:
gateway:
routes:
– id: example_route
uri: http://httpbin.org
predicates:
– Path=/example/**
filters:
– RewritePath=/example/(?.*), /${path}

# 启动类
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}

# 添加依赖


org.springframework.cloud
spring-cloud-starter-gateway


org.springframework.cloud
spring-cloud-starter-netflix-eureka-client

6.3 Spring Cloud Gateway 过滤器

# 自定义过滤器
@Component
public class CustomFilter implements GlobalFilter, Ordered {
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 前置处理
System.out.println(“Before filter”);

return chain.filter(exchange).then(Mono.fromRunnable(() -> {
// 后置处理
System.out.println(“After filter”);
}));
}

@Override
public int getOrder() {
return -1;
}
}

更多学习教程公众号风哥教程itpux_com

7. Nginx作为API网关

7.1 Nginx 配置

# nginx.conf
http {
upstream backend {
server backend1:8080;
server backend2:8080;
server backend3:8080;
}

server {
listen 80;
server_name api.fgedu.net.cn;

location /api/ {
proxy_pass http://backend/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# 限流
limit_req_zone $binary_remote_addr zone=api:10m rate=1r/s;
limit_req zone=api burst=5 nodelay;

# 认证
auth_basic “Restricted”;
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
}

7.2 Nginx 限流配置

# 配置限流
limit_req_zone $binary_remote_addr zone=api:10m rate=1r/s;

server {
listen 80;
server_name api.fgedu.net.cn;

location /api/ {
limit_req zone=api burst=5 nodelay;
proxy_pass http://backend/;
}
}

7.3 Nginx 缓存配置

# 配置缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
listen 80;
server_name api.fgedu.net.cn;

location /api/ {
proxy_cache api_cache;
proxy_cache_valid 200 60m;
proxy_cache_key “$host$request_uri”;
proxy_pass http://backend/;
}
}

风哥风哥提示:Nginx作为API网关时,需要注意配置的优化,以确保性能和可靠性。

8. API网关部署

8.1 容器化部署

# Dockerfile
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80

# 构建镜像
$ docker build -t api-gateway .

# 运行容器
$ docker run -d –name api-gateway -p 80:80 api-gateway

8.2 Kubernetes部署

# api-gateway-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-gateway
labels:
app: api-gateway
spec:
replicas: 3
selector:
matchLabels:
app: api-gateway
template:
metadata:
labels:
app: api-gateway
spec:
containers:
– name: api-gateway
image: api-gateway:latest
ports:
– containerPort: 80
resources:
limits:
cpu: “1”
memory: “512Mi”
requests:
cpu: “500m”
memory: “256Mi”

apiVersion: v1
kind: Service
metadata:
name: api-gateway
spec:
selector:
app: api-gateway
ports:
– port: 80
targetPort: 80
type: LoadBalancer

8.3 高可用部署

  • 多实例部署:部署多个API网关实例,通过负载均衡分发流量
  • 跨区域部署:在不同区域部署API网关,提高可用性
  • 自动扩缩容:根据流量自动调整API网关实例数量

学习交流加群风哥QQ113257174

9. API网关安全

9.1 认证与授权

# Kong认证插件配置
$ curl -X POST http://fgedudb:8001/services/example-service/plugins \
–data “name=key-auth”

# 创建API密钥
$ curl -X POST http://fgedudb:8001/consumers \
–data “username=user1”

$ curl -X POST http://fgedudb:8001/consumers/user1/key-auth \
–data “key=secret123”

# 测试认证
$ curl -i http://fgedudb:8000/example/get

$ curl -i http://fgedudb:8000/example/get -H “apikey: secret123”

HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Connection: keep-alive
WWW-Authenticate: Key realm=”kong”
Date: Sat, 03 Apr 2026 00:00:00 GMT
Content-Length: 41
Server: kong/2.6.0

{“message”:”No API key found in request”}

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 314
Connection: keep-alive
Date: Sat, 03 Apr 2026 00:00:00 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Server: gunicorn/19.9.0
Kong-Request-Id: 1234567890abcdef1234567890abcdef
X-Kong-Upstream-Latency: 100
X-Kong-Proxy-Latency: 10
Via: kong/2.6.0

{
“args”: {},
“headers”: {
“Accept”: “*/*”,
“Host”: “httpbin.org”,
“User-Agent”: “curl/7.64.1”,
“X-Forwarded-Host”: “fgedudb”
},
“origin”: “172.17.0.1, 1.2.3.4”,
“url”: “http://httpbin.org/get”
}

9.2 限流与熔断

# Kong限流插件配置
$ curl -X POST http://fgedudb:8001/services/example-service/plugins \
–data “name=rate-limiting” \
–data “config.minute=10” \
–data “config.hour=100”

# 测试限流
$ for i in {1..15}; do curl -i http://fgedudb:8000/example/get -H “apikey: secret123”; done

9.3 SSL/TLS配置

# Nginx SSL配置
server {
listen 443 ssl;
server_name api.fgedu.net.cn;

ssl_certificate /etc/nginx/ssl/api.fgedu.net.cn.crt;
ssl_certificate_key /etc/nginx/ssl/api.fgedu.net.cn.key;

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_prefer_server_ciphers on;

location /api/ {
proxy_pass http://backend/;
}
}

更多学习教程www.fgedu.net.cn

10. API网关最佳实践

10.1 设计最佳实践

  • API版本管理:使用URL路径或HTTP头进行版本控制
  • API文档:使用OpenAPI规范文档化API
  • 错误处理:统一错误响应格式
  • 请求/响应格式:使用JSON或XML等标准格式

10.2 性能最佳实践

  • 缓存:缓存频繁访问的API响应
  • 限流:合理设置限流规则,防止过载
  • 连接池:使用连接池管理后端服务连接
  • 压缩:启用HTTP压缩,减少传输数据量

10.3 安全最佳实践

  • 使用HTTPS:加密传输数据
  • 实施认证和授权:确保只有合法用户能够访问API
  • 输入验证:验证所有用户输入,防止注入攻击
  • 定期更新:及时更新API网关和依赖库

10.4 监控最佳实践

  • 日志记录:记录API调用日志,便于问题排查
  • 指标监控:监控API调用次数、错误率、延迟等指标
  • 告警:设置合理的告警规则,及时发现问题
  • 分布式追踪:使用分布式追踪工具,跟踪请求流程
生产环境风哥建议:

  • 选择适合自己业务场景的API网关解决方案
  • 实施完善的监控和告警系统
  • 定期进行安全审计和渗透测试
  • 建立API网关的灾备方案
  • 持续优化API网关配置,提高性能和可靠性

author:www.itpux.com

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息