3. Kubernetes 的 DiscoveryClient
本项目为 发现客户端 提供了针对 Kubernetes 的实现。该客户端可让您通过名称查询 Kubernetes 端点(参见 服务)。服务通常由 Kubernetes API 服务器以一组端点形式暴露,这些端点代表 http 和 https 地址,客户端可在作为 Pod 运行的 Spring Boot 应用程序中访问这些地址。
This is something that you get for free by adding the following dependency inside your project:
基于 HTTP 的 DiscoveryClient
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-discoveryclient</artifactId>
</dependency>
spring-cloud-starter-kubernetes-discoveryclient 是专为与 Spring Cloud Kubernetes DiscoveryServer 配合使用而设计的。 |
Fabric8 Kubernetes Client
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-fabric8</artifactId>
</dependency>
Kubernetes Java 客户端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-client</artifactId>
</dependency>
要启用加载 DiscoveryClient,请将 @EnableDiscoveryClient 添加到相应的配置或应用类中,如下例所示:
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后,您只需通过自动装配(autowiring)即可在代码中注入客户端,如下例所示:
@Autowired
private DiscoveryClient discoveryClient;
你可以通过在application.properties中设置以下属性来启用所有命名空间的DiscoveryClient:
spring.cloud.kubernetes.discovery.all-namespaces=true
要发现由 Kubernetes API 服务器标记为“就绪”的服务端点地址,请在application.properties中设置以下属性(默认值:false):
spring.cloud.kubernetes.discovery.include-not-ready-addresses=true
这可能在发现服务用于监视目的很有用,并且可以检查未就绪服务实例的/health端点。 |
如果您的服务暴露多个端口,您需要指定DiscoveryClient应使用的端口。
DiscoveryClient将使用以下逻辑选择端口。
-
如果服务有一个标签
primary-port-name,它将使用名称在标签值中指定的端口。 -
如果未指定标签,则将使用在
spring.cloud.kubernetes.discovery.primary-port-name中指定的端口名称。 -
如果以上两者都不是指定的,它会使用名为
https的端口。 -
如果以上所有条件都不满足,它将使用端口
http。 -
作为最后的手段,它会选择端口列表中的第一个端口。
| 最后一个选项可能会导致非确定性行为。请确保相应地配置服务和/或应用程序。 |
默认情况下,所有端口及其名称都会添加到索引为 ServiceInstance 的元数据中。
如果出于任何原因,您需要禁用DiscoveryClient,则可在application.properties中设置以下属性:
spring.cloud.kubernetes.discovery.enabled=false
某些Spring Cloud组件使用DiscoveryClient来获取有关本地服务实例的信息。为此,您需要使Kubernetes服务名与spring.application.name属性保持一致。
spring.application.name 对在 Kubernetes 中为应用程序注册的名称没有影响 |
Spring Cloud Kubernetes 还可以监视 Kubernetes 服务目录中的更改,并相应地更新 0 实现。 要启用此功能,您需要在应用程序的配置类中添加 1 。