跳至内容

鸭子类型

Knative 通过使用松耦合来实现其组件的鸭子类型

鸭子类型意味着,资源在 Knative 系统中使用的兼容性由用于识别资源控制平面形状和行为的某些属性决定。这些属性基于一组针对不同类型资源的通用定义,称为鸭子类型。

如果 Knative 可以像通用鸭子类型一样使用资源,而无需了解资源类型,则

  • 资源在与通用定义相同的模式位置具有相同的字段
  • 与通用定义相同的控制或数据平面行为

某些资源可以选择加入多个鸭子类型。

Knative 中鸭子类型的一个基本用途是在资源 *规范* 中使用对象引用来指向其他资源。包含引用的对象的定义规定了被引用资源的预期鸭子类型。

示例

在以下示例中,名为 pointer 的 Knative Example 资源在其规范中引用了名为 pointeeDog 资源

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 资源能够应用为其配置的逻辑,而无需明确了解 HumanDog

Knative 鸭子类型

Knative 定义了在整个项目中使用的一些鸭子类型契约

Addressable

Addressable 预计将具有以下形状

apiVersion: group/version
kind: Kind
status:
  address:
    url: http://host/path?query

Binding

使用直接 subject,Binding 预计将具有以下形状

apiVersion: group/version
kind: Kind
spec:
  subject:
    apiVersion: group/version
    kind: SomeKind
    namespace: the-namespace
    name: a-name

使用间接 subject,Binding 预计将具有以下形状

apiVersion: group/version
kind: Kind
spec:
  subject:
    apiVersion: group/version
    kind: SomeKind
    namespace: the-namespace
    selector:
      matchLabels:
        key: value

Source

使用 ref Sink,Source 预计将具有以下形状

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,Source 预计将具有以下形状

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

使用 refuri Sinks,Source 预计将具有以下形状

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

我们使用分析和 Cookie 来了解网站流量。有关您使用我们网站的信息将与 Google 共享,以供该目的使用。 了解更多。