Spring Cloud學習02--Ribbon基本使用
阿新 • • 發佈:2020-12-13
Ribbon功能:提供雲端負載均衡,有多種負載均衡策略可供選擇,可配合服務發現和斷路器使用。
Ribbon是一種客戶端負載均衡工具,而Dubbo是服務端負載均衡工具。
在上文的專案基礎上,繼續新增Ribbon的功能。
1.啟動兩個search模組:
在03-search專案的專案啟動下拉框中,選擇edit功能:
選中03-search專案,點選上方的複製按鈕,複製一個啟動項:
修改新複製的search專案的啟動項,名稱修改為SearchApplication 8082,新增啟動引數:-Dserver.port=8082
修改好之後,啟動這兩個search專案,通過瀏覽器,分別訪問:http://localhost:8081/search與http://localhost:8082:search
均可正常訪問,則說明此啟動項複製和配置是正確的。
2.修改02-customer專案:
在customer專案的pom檔案中,新增Ribbon的引用:
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework.cloud</groupId> 4 <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> 5 </dependency> 6 <dependency> 7 <groupId>org.springframework.cloud</groupId> 8 <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> 9 </dependency> 10 <dependency> 11 <groupId>org.springframework.boot</groupId> 12 <artifactId>spring-boot-starter-web</artifactId> 13 </dependency> 14 </dependencies>
修改啟動類,為RestTemplate物件新增@LoadBalanced註解:
1 package com.yangasen; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.cloud.client.loadbalancer.LoadBalanced; 6 import org.springframework.cloud.netflix.eureka.EnableEurekaClient; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.web.client.RestTemplate; 9 10 11 @SpringBootApplication 12 @EnableEurekaClient 13 public class CustomerApplication { 14 public static void main(String[] args) { 15 SpringApplication.run(CustomerApplication.class,args); 16 } 17 @Bean 18 @LoadBalanced 19 public RestTemplate restTemplate(){ 20 return new RestTemplate(); 21 } 22 }
修改Controller程式碼:
1 package com.yangasen.controller; 2 3 import com.netflix.appinfo.InstanceInfo; 4 import com.netflix.discovery.EurekaClient; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.web.bind.annotation.GetMapping; 7 import org.springframework.web.bind.annotation.RestController; 8 import org.springframework.web.client.RestTemplate; 9 10 @RestController 11 public class CustomerController { 12 13 @Autowired 14 private RestTemplate restTemplate; 15 16 @Autowired 17 private EurekaClient eurekaClient; 18 19 @GetMapping("/customer") 20 public String customer(){ 21 String result = restTemplate.getForObject("http://SEARCH/search",String.class); 22 return result; 23 } 24 }
3.測試效果:
啟動eureka服務和customer,在瀏覽器中訪問:http://localhost:8080/customer
顯示如下效果:
再次重新整理此頁面,訪問埠發生變化:
Robbin的預設配置,是採用輪詢的方式進行負載均衡。