直接使用Ribbon API ?您也可以直接使用LoadBalancerClient。例:
public class MyClass {
? ? @Autowired
? ? private LoadBalancerClient loadBalancer;
? ? public void doStuff() {
? ? ? ? ServiceInstance instance = loadBalancer.choose("stores");
? ? ? ? URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
? ? ? ? // ... do something with the URI
? ? }
}
緩存Ribbon配置
每個Ribbon命名的客戶端都有一個相應的子應用程序上下文,Spring Cloud維護,這個應用程序上下文在第一個請求中被延遲加載到命名的客戶端。可以通過指定Ribbon客戶端的名稱,在啟動時,可以更改此延遲加載行為,從而熱切加載這些子應用程序上下文。
application.yml
ribbon:
? eager-load:
? ? enabled: true
? ? clients: client1, client2, client3
聲明性REST客戶端:Feign
Feign是一個聲明式的Web服務客戶端。這使得Web服務客戶端的寫入更加方便?要使用Feign創建一個界面并對其進行注釋。它具有可插入注釋支持,包括Feign注釋和JAX-RS注釋。Feign還支持可插拔編碼器和解碼器。Spring Cloud增加了對Spring MVC注釋的支持,并使用Spring Web中默認使用的HttpMessageConverters。Spring Cloud集成Ribbon和Eureka以在使用Feign時提供負載均衡的http客戶端。
如何加入Feign
要在您的項目中包含Feign,請使用組org.springframework.cloud和工件IDspring-cloud-starter-feign的啟動器。有關?使用當前的Spring Cloud發布列表設置構建系統的詳細信息,請參閱Spring Cloud項目頁面。
示例spring boot應用
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients
public class Application {
? ? public static void main(String[] args) {
? ? ? ? SpringApplication.run(Application.class, args);
? ? }
}
StoreClient.java
@FeignClient("stores")
public interface StoreClient {
? ? @RequestMapping(method = RequestMethod.GET, value = "/stores")
? ? List getStores();
? ? @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
? ? Store update(@PathVariable("storeId") Long storeId, Store store);
}
在@FeignClient注釋中,String值(以上“存儲”)是一個任意的客戶端名稱,用于創建Ribbon負載平衡器(有關Ribbon支持的詳細信息,請參閱下文))。您還可以使用url屬性(絕對值或只是主機名)指定URL。應用程序上下文中的bean的名稱是該接口的完全限定名稱。要指定您自己的別名值,您可以使用@FeignClient注釋的qualifier值。
以上的Ribbon客戶端將會發現“商店”服務的物理地址。如果您的應用程序是Eureka客戶端,那么它將解析Eureka服務注冊表中的服務。如果您不想使用Eureka,您可以簡單地配置外部配置中的服務器列表(例如,參見?上文)。