Spring Cloud Kubernetes的DiscoveryClient

2024-01-08 17:18 更新

該項(xiàng)目提供了KubernetesDiscovery Client實(shí)現(xiàn)。通過此客戶端,您可以按名稱查詢Kubernetes端點(diǎn)(請(qǐng)參閱服務(wù))。Kubernetes API服務(wù)器通常將服務(wù)公開為代表httphttps地址的端點(diǎn)的集合,并且客戶端可以從作為Pod運(yùn)行的Spring Boot應(yīng)用程序進(jìn)行訪問。 Spring Cloud Kubernetes Ribbon項(xiàng)目也使用此發(fā)現(xiàn)功能來獲取為要進(jìn)行負(fù)載平衡的應(yīng)用程序定義的端點(diǎn)列表。

您可以通過在項(xiàng)目內(nèi)部添加以下依賴項(xiàng)來免費(fèi)獲得這些東西:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-kubernetes</artifactId>
</dependency>

要啟用DiscoveryClient的加載,請(qǐng)將@EnableDiscoveryClient添加到相應(yīng)的配置或應(yīng)用程序類中,如以下示例所示:

@SpringBootApplication
@EnableDiscoveryClient
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

然后,您可以簡單地通過自動(dòng)裝配將客戶端注入代碼中,如以下示例所示:

@Autowired
private DiscoveryClient discoveryClient;

您可以通過在application.properties中設(shè)置以下屬性來選擇從所有命名空間啟用DiscoveryClient

spring.cloud.kubernetes.discovery.all-namespaces=true

如果出于任何原因需要禁用DiscoveryClient,則可以在application.properties中設(shè)置以下屬性:

spring.cloud.kubernetes.discovery.enabled=false

某些Spring Cloud組件使用DiscoveryClient來獲取有關(guān)本地服務(wù)實(shí)例的信息。為此,您需要將Kubernetes服務(wù)名稱與spring.application.name屬性對(duì)齊。

spring.application.name對(duì)在Kubernetes中為該應(yīng)用程序注冊(cè)的名稱無效

Spring Cloud Kubernetes也可以監(jiān)視Kubernetes服務(wù)目錄中的更改并相應(yīng)地更新DiscoveryClient實(shí)現(xiàn)。為了啟用此功能,您需要在應(yīng)用程序的配置類上添加@EnableScheduling


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)