前提条件
- 已开通云容器引擎,至少有一个云容器引擎集群实例。产品入口:云容器引擎。
- 开通天翼云服务网格实例。
操作步骤
gRPC是远程过程调用框架(RPC),有多语言的实现,底层采用HTTP2作为传输协议;由于HTTP2采用长连接机制,在负载均衡的场景下可能导致负载的不平衡,本文介绍负载不均衡的场景以及如何通过服务网格实现负载均衡。
部署gRPC server和client应用。
apiVersion: apps/v1
kind: Deployment
metadata:
name: grpc-server-v1
labels:
app: grpc-server
version: v1
spec:
replicas: 1
selector:
matchLabels:
app: grpc-server
version: v1
template:
metadata:
labels:
app: grpc-server
version: v1
spec:
containers:
- args:
- --address=0.0.0.0:8080
image: registry-vpc-crs-huadong1.cnsp-internal.ctyun.cn/library/grpc-server
imagePullPolicy: Always
name: grpc-server
ports:
- containerPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: grpc-server-v2
labels:
app: grpc-server
version: v2
spec:
replicas: 1
selector:
matchLabels:
app: grpc-server
version: v2
template:
metadata:
labels:
app: grpc-server
version: v2
spec:
containers:
- args:
- --address=0.0.0.0:8080
image: registry-vpc-crs-huadong1.cnsp-internal.ctyun.cn/library/grpc-server
imagePullPolicy: Always
name: grpc-server
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: grpc-server
labels:
app: grpc-server
spec:
ports:
- name: grpc-backend
port: 8080
protocol: TCP
selector:
app: grpc-server
type: ClusterIP
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: grpc-client
labels:
app: grpc-client
spec:
replicas: 1
selector:
matchLabels:
app: grpc-client
template:
metadata:
labels:
app: grpc-client
"sidecar.istio.io/inject": "true"
spec:
containers:
- image: registry-vpc-crs-huadong1.cnsp-internal.ctyun.cn/library/grpc-client
imagePullPolicy: Always
command: ["/bin/sleep", "3650d"]
name: grpc-client
---
部署之后的pod列表(一个client,两个版本的server):
通过client访问server,可以看到总是访问服务端的同一个实例。
kubectl exec -it grpc-client-b7499b9c-45d2s -n grpc --
/bin/greeter-client --insecure=true --address=grpc-server:8080 --repeat=10
为grpc client注入sidecar(打上标签"sidecar.istio.io/inject": "true"),重新部署grpc-client之后可以看到pod列表如下:
再次通过grpc-client访问grpc-server可以看到请求交替访问两个版本的grpc-server:
部署流量治理策略使70%的流量访问v2版本的grpc-server,30%的流量访问v1版本的grpc-server。
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: dr-grpc-server
spec:
host: grpc-server
trafficPolicy:
loadBalancer:
simple: ROUND_ROBIN
subsets:
- name: v1
labels:
version: "v1"
- name: v2
labels:
version: "v2"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: vs-grpc-server
spec:
hosts:
- "grpc-server"
http:
- match:
- port: 8080
route:
- destination:
host: grpc-server
subset: v1
weight: 30
- destination:
host: grpc-server
subset: v2
weight: 70
再次访问可以看到请求在grpc-server的两个版本之间不再是交替访问,而是大概按照7:3的比例访问: