第 13 章 · 服务网格与 Istio 概念
本章目标:理解 服务网格(Service Mesh) 解决什么问题;掌握 数据平面(Sidecar) 与 控制平面 分工;阅读虚构 svc-spring-demo on Istio 的 VirtualService / DestinationRule YAML;对比 Spring Cloud Gateway + Feign 与 Istio 的流量治理能力;了解 mTLS、熔断重试在 Sidecar 层的实现;为 xiaozi-cloud K8s 运维打基础。
学时建议:4~5 小时(以概念与 YAML 阅读为主,本地 Istio 选修)
前置:spring-cloud-web ch01~ch12;xiaozi-cloud ch01~ch03 K8s 基础(或同等 kubectl 知识)。
13.1 从 Spring Cloud 到 Service Mesh
ch03~ch05 在应用代码中实现:Gateway 路由、Feign 负载均衡、Resilience4j 熔断。
传统 Spring Cloud:
┌─────────────┐ Feign+LB ┌─────────────┐
│ order-svc │────────────►│ product-svc │
│ 内置熔断 │ │ │
└─────────────┘ └─────────────┘
Service Mesh:
┌─────────────┐ ┌─────────────┐
│ order-svc │ │ product-svc │
└──────┬──────┘ └──────┬──────┘
│ Envoy Sidecar │ Envoy Sidecar
└───────────┬──────────────┘
│ mTLS、重试、指标
┌────┴────┐
│ Istiod │ 控制平面
└─────────┘
| 能力 | Spring Cloud 位置 | Istio 位置 |
|---|---|---|
| 路由 | Gateway YAML | VirtualService |
| 负载均衡 | LoadBalancer | Sidecar 代理 |
| 熔断重试 | Resilience4j | DestinationRule |
| mTLS | 需自行配置 | 默认可启用 |
| 指标追踪 | Micrometer | Envoy + OTel |
结论:Mesh 将网络横切能力下沉到基础设施,应用代码更「纯业务」;但引入 Sidecar 资源开销与运维复杂度。
13.2 Istio 核心组件
| 组件 | 类型 | 职责 |
|---|---|---|
| istiod | 控制平面 | 配置分发、证书、服务发现 |
| Envoy | 数据平面 Sidecar | 每 Pod 注入,代理进出流量 |
| Gateway | Ingress | 集群入口(类似 K8s Ingress 增强) |
| VirtualService | 路由规则 | 匹配 Host/Header,转发权重 |
| DestinationRule | 目标策略 | 子集、熔断、TLS 模式 |
Internet
│
▼
Istio Ingress Gateway
│
▼ VirtualService: api.example.com
┌───────────────────────────────────┐
│ K8s Namespace: svc-spring │
│ ┌─────────┐ ┌─────────┐ │
│ │order Pod│◄────►│product │ │
│ │+ Envoy │ mTLS │+ Envoy │ │
│ └─────────┘ └─────────┘ │
└───────────────────────────────────┘
13.3 在 K8s 部署 svc-spring-demo(概念)
假设各服务已容器化(ch19),Namespace svc-spring:
# 选修:本地 minikube/k3s
istioctl install --set profile=demo -y
kubectl label namespace svc-spring istio-injection=enabled
kubectl apply -f deploy/k8s/
Sidecar 自动注入后,Pod 变为 2 容器:order-svc + istio-proxy。
13.4 VirtualService:路由与灰度(预习 ch15)
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: product-svc
namespace: svc-spring
spec:
hosts:
- product-svc
http:
- match:
- headers:
x-canary:
exact: "true"
route:
- destination:
host: product-svc
subset: v2
weight: 100
- route:
- destination:
host: product-svc
subset: v1
weight: 90
- destination:
host: product-svc
subset: v2
weight: 10
与 ch15 灰度发布按权重分流的思想一致,但规则在平台层声明,无需修改应用代码。
13.5 DestinationRule:子集与熔断
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: product-svc
namespace: svc-spring
spec:
host: product-svc