3. Kubernetes 的 DiscoveryClient
该项目提供了 Discovery Client for Kubernetes 的实现。
此客户端允许您按名称查询 Kubernetes 终端节点(请参阅服务)。
服务通常由 Kubernetes API 服务器作为端点的集合公开,这些端点代表http
和https
addresses 的地址,并且客户端可以
从作为 Pod 运行的 Spring Boot 应用程序访问。
这是您可以通过在项目中添加以下依赖项来免费获得的东西:
Fabric8 Kubernetes 客户端
<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
添加到相应的 Configuration 或 Application 类中,如下例所示:
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后,您只需通过自动装配客户端即可将其注入代码中,如下例所示:
@Autowired
private DiscoveryClient discoveryClient;
您可以选择启用DiscoveryClient
通过在application.properties
:
spring.cloud.kubernetes.discovery.all-namespaces=true
要发现未被 kubernetes api 服务器标记为 “ready” 的服务端点地址,您可以在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 服务目录的更改,并更新DiscoveryClient
相应地实施。要启用此功能,您需要添加@EnableScheduling
在应用程序中的 Configuration 类上。