SpringCloud 自定義Ribbon客戶端

2023-11-22 14:00 更新

您可以使用<client>.ribbon.*中的外部屬性來配置Ribbon客戶端的某些位,這與本地使用Netflix API相似,不同之處在于可以使用Spring Boot配置文件。可以將本機(jī)選項(xiàng)檢查為CommonClientConfigKey(功能區(qū)核心的一部分)中的靜態(tài)字段。

Spring Cloud還允許您通過使用@RibbonClient聲明其他配置(在RibbonClientConfiguration之上)來完全控制客戶端,如以下示例所示:

@Configuration
@RibbonClient(name = "custom", configuration = CustomConfiguration.class)
public class TestConfiguration {
}

在這種情況下,客戶端由RibbonClientConfiguration中已有的組件以及CustomConfiguration中的任何組件組成(其中后者通常會(huì)覆蓋前者)。

CustomConfiguration類必須是@Configuration類,但請(qǐng)注意,對(duì)于主應(yīng)用程序上下文,它不在@ComponentScan中。否則,它由所有@RibbonClients共享。如果您使用@ComponentScan(或@SpringBootApplication),則需要采取措施避免將其包括在內(nèi)(例如,可以將其放在單獨(dú)的,不重疊的程序包中,或指定要在@ComponentScan)。

下表顯示了Spring Cloud Netflix默認(rèn)為Ribbon提供的beans:

Bean類型 Bean名稱 班級(jí)名稱

IClientConfig

ribbonClientConfig

DefaultClientConfigImpl

IRule

ribbonRule

ZoneAvoidanceRule

IPing

ribbonPing

DummyPing

ServerList<Server>

ribbonServerList

ConfigurationBasedServerList

ServerListFilter<Server>

ribbonServerListFilter

ZonePreferenceServerListFilter

ILoadBalancer

ribbonLoadBalancer

ZoneAwareLoadBalancer

ServerListUpdater

ribbonServerListUpdater

PollingServerListUpdater

創(chuàng)建其中一種類型的bean并將其放置在@RibbonClient配置中(例如上述FooConfiguration),您可以覆蓋所描述的每個(gè)beans,如以下示例所示:

@Configuration
protected static class FooConfiguration {

	@Bean
	public ZonePreferenceServerListFilter serverListFilter() {
		ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter();
		filter.setZone("myTestZone");
		return filter;
	}

	@Bean
	public IPing ribbonPing() {
		return new PingUrl();
	}

}

上一示例中的include語句將NoOpPing替換為PingUrl,并提供了自定義serverListFilter

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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)