在Spring Cloud Commons中提供了大量的與服務治理相關的抽象接口,包括DiscoveryClient
、這裏咱們即將介紹的LoadBalancerClient
等。對於這些接口的定義咱們在上一篇介紹服務註冊與發現時已經說過,Spring Cloud作這一層抽象,很好的解耦了服務治理體系,使得咱們能夠輕易的替換不一樣的服務治理設施。html
從LoadBalancerClient
接口的命名中,咱們就知道這是一個負載均衡客戶端的抽象定義,下面咱們就看看如何使用Spring Cloud提供的負載均衡器客戶端接口來實現服務的消費。web
下面的例子,咱們將利用上一篇中構建的eureka-server做爲服務註冊中心、eureka-client做爲服務提供者做爲基礎。spring
eureka-consumer
。並在pom.xml
中引入依賴(這裏省略了parent和dependencyManagement的配置): 1架構 2app 3負載均衡 4框架 5函數 6spring-boot 7微服務 8 9 10 11 12 13 14 |
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> |
application.properties
,指定eureka註冊中心的地址: 1 2 3 4 |
spring.application.name=eureka-consumer server.port=2101 eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/ |
RestTemplate
,用來真正發起REST請求。@EnableDiscoveryClient
註解用來將當前應用加入到服務治理體系中。 1 2 3 4 5 6 7 8 9 10 11 12 13 |
@EnableDiscoveryClient @SpringBootApplication public class Application { public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@RestController public class DcController { @Autowired LoadBalancerClient loadBalancerClient; @Autowired RestTemplate restTemplate; @GetMapping("/consumer") public String dc() { ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-client"); String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc"; System.out.println(url); return restTemplate.getForObject(url, String.class); } } |
能夠看到這裏,咱們注入了LoadBalancerClient
和RestTemplate
,並在/consumer
接口的實現中,先經過loadBalancerClient
的choose
函數來負載均衡的選出一個eureka-client
的服務實例,這個服務實例的基本信息存儲在ServiceInstance
中,而後經過這些對象中的信息拼接出訪問/dc
接口的詳細地址,最後再利用RestTemplate
對象實現對服務提供者接口的調用。
在完成了上面你的代碼編寫以後,讀者能夠將eureka-server、eureka-client、eureka-consumer都啓動起來,來跟蹤觀察eureka-consumer服務是如何消費eureka-client服務的/dc
接口的。
從如今開始,我這邊會將近期研發的springcloud微服務雲架構的搭建過程和精髓記錄下來,幫助更多有興趣研發spring cloud框架的朋友,但願能夠幫助更多的好學者。你們來一塊兒探討spring cloud架構的搭建過程及如何運用於企業項目。源碼來源