鴨子類型 (Duck typing)¶
鴨子類型表示在 Knative 系統中,資源的相容性是由某些用於識別資源控制平面形狀和行為的屬性來決定的。這些屬性基於不同類型資源的一組通用定義,稱為鴨子類型。
如果滿足以下條件,Knative 可以像使用通用鴨子類型一樣使用資源,而無需了解資源的具體類型:
- 資源在與通用定義指定的相同架構位置中具有相同的欄位
- 具有與通用定義指定的相同的控制或資料平面行為
有些資源可以選擇加入多種鴨子類型。
在 Knative 中,鴨子類型的一個基本用途是在資源 *規格 (specs)* 中使用物件參考來指向其他資源。包含參考的物件的定義規定了被參考資源的預期鴨子類型。
範例¶
在以下範例中,名為 pointer
的 Knative Example
資源在其規格中參考了名為 pointee
的 Dog
資源
apiVersion: sample.knative.dev/v1
kind: Example
metadata:
name: pointer
spec:
size:
apiVersion: extension.example.com/v1
kind: Dog
name: pointee
如果 Sizable 鴨子類型的預期形狀是,在 status
中,架構形狀如下:
status:
height: <in centimetres>
weight: <in kilograms>
現在 pointee
的實例可能如下所示:
apiVersion: extension.example.com/v1
kind: Dog
metadata:
name: pointee
spec:
owner: Smith Family
etc: more here
status:
lastFeeding: 2 hours ago
hungry: true
age: 2
height: 60
weight: 20
當 Example
資源運作時,它只作用於 Sizable 鴨子類型形狀中的資訊,而 Dog
實作可以自由地擁有對該資源最有意義的資訊。當我們使用新的類型(例如 Human
)擴展系統時,鴨子類型的強大之處就顯而易見了,如果新資源遵守 Sizable 設定的契約。
apiVersion: sample.knative.dev/v1
kind: Example
metadata:
name: pointer
spec:
size:
apiVersion: people.example.com/v1
kind: human
name: pointee
---
apiVersion: people.example.com/v1
kind: Human
metadata:
name: pointee
spec:
etc: even more here
status:
college: true
hungry: true
age: 22
height: 170
weight: 50
Example
資源能夠應用為其配置的邏輯,而無需明確了解 Human
或 Dog
。
Knative 鴨子類型¶
Knative 定義了專案中使用的幾種鴨子類型契約
可定址 (Addressable)¶
可定址預期具有以下形狀:
apiVersion: group/version
kind: Kind
status:
address:
url: http://host/path?query
繫結 (Binding)¶
使用直接 subject
,繫結預期具有以下形狀:
apiVersion: group/version
kind: Kind
spec:
subject:
apiVersion: group/version
kind: SomeKind
namespace: the-namespace
name: a-name
使用間接 subject
,繫結預期具有以下形狀:
apiVersion: group/version
kind: Kind
spec:
subject:
apiVersion: group/version
kind: SomeKind
namespace: the-namespace
selector:
matchLabels:
key: value
來源 (Source)¶
使用 ref
Sink,來源預期具有以下形狀:
apiVersion: group/version
kind: Kind
spec:
sink:
ref:
apiVersion: group/version
kind: AnAddressableKind
name: a-name
ceOverrides:
extensions:
key: value
status:
observedGeneration: 1
conditions:
- type: Ready
status: "True"
sinkUri: http://host
使用 uri
Sink,來源預期具有以下形狀:
apiVersion: group/version
kind: Kind
spec:
sink:
uri: http://host/path?query
ceOverrides:
extensions:
key: value
status:
observedGeneration: 1
conditions:
- type: Ready
status: "True"
sinkUri: http://host/path?query
使用 ref
和 uri
Sinks,來源預期具有以下形狀:
apiVersion: group/version
kind: Kind
spec:
sink:
ref:
apiVersion: group/version
kind: AnAddressableKind
name: a-name
uri: /path?query
ceOverrides:
extensions:
key: value
status:
observedGeneration: 1
conditions:
- type: Ready
status: "True"
sinkUri: http://host/path?query