ps:istio
的官方提供的 bookinfo
例子已經很齊全了,但我很討厭拿 bookinfo
當作示例。因爲是別人已經提供好的,包括 yaml
文件你自己根本沒有從中學習到什麼,所以想自己寫一些 demo
、yaml
來使用。
step1: 前提
在這裏默認你已經自己提供了 demo,纔可以往下進行。demo 可以如下圖所示:
中間三個 pod 是我自己提供的 demo 其他的請無視。java-demo-client 是客戶端,會調用 java-demo-service 服務端,服務端我提供了兩個版本 v1、v2 版本。現在訪問一下確定一下部署是否成功了
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v2
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v2
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v2
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
這個時候已經是默認的輪詢了。
step2: 創建 DestinationRule
如果想要控制路由就必須創建 VirtualService
,VirtualService
實現如何匹配一個流量的路由,DestinationRule
則是定義了收到流量之後做什麼?
如果結合使用的話 VirtualService
中的 subset
也需要在 DestinationRule
中定義。重要的內容已經在 yaml
中使用註釋表明了。
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: demo-default
namespace: default
spec:
# 注意: 如果創建 DestinationRule 沒有指定負載均衡算法,此時就是默認的輪詢算法,其他還有隨機、最少連接、還有一個我忘了
# 規則的目標
host: java-demo-service
subsets:
- name: v1
labels:
# DestinationRule 將匹配下面這個標籤的 pod 定義爲 v1 版本
version: v1
- name: v2
labels:
# DestinationRule 將匹配下面這個標籤的 pod 定義爲 v2 版本
version: v2
kubectl apply -f destinationrule.yaml
kubectl get dr -n default
好的,下發成功。
step3: 創建 VirtualService
VirtualService
來更細粒度的匹配請求 DestinationRule
來處理這些請求,下面是定義路由。
下面就是一個最基本的路由,將所有的請求轉發到 java-demo-service 的 v1 版本。同樣比較重要的提供已經註釋提示。
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: demo-default
namespace: default
spec:
hosts:
# 規則的目標
- java-demo-service
http:
- route:
- destination:
host: java-demo-service
# DestinationRule 同樣需要定義 v1
subset: v1
kubectl apply -f virtualservice-all-v1.yaml
step4: 測試
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
[root@node4 simple]# curl 10.96.87.54:8083/demo/client/hello?name=zhangsan
張三小企業一v1
沒有問題,此時所有的流量都已經轉發到 v1 版本。如果需要轉發到 v2 的話,更新一下 yaml
文件然後 apply
即可,直接使用 edit
編輯 virtualservice
也行,沒了。