1 Ribbon簡介
Ribbon是Netflix發(fā)布的基于HTTP和TCP的客戶端負(fù)載均衡器踢关,為Ribbon配置服務(wù)提供者的地址列表后,Ribbon就可以基于某種負(fù)載均衡算法诵叁,自動(dòng)地幫助服務(wù)消費(fèi)者去請(qǐng)求优俘。在Spring Cloud 中饥努, 當(dāng)Ribbon與Eureka配合使用時(shí)胳泉,Ribbon可以自動(dòng)從Eureka Server中獲取服務(wù)提供者地址列表,并基于負(fù)載均衡算法们何,請(qǐng)求其中一個(gè)服務(wù)提供者實(shí)例陶因。
2 Eureka整合Ribbon
- 添加相應(yīng)的依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
- 服務(wù)消費(fèi)者也是一個(gè)Eureka Client,同樣需要聲明
@EnableDiscoveryClient
垂蜗,另外需要初始化RestTemplate,添加@LoadBalanced
實(shí)現(xiàn)負(fù)載均衡
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonDemoApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonDemoApplication.class, args);
}
}
在這里已經(jīng)整合完畢解幽,這時(shí)為我們就可以用微服務(wù)的虛擬主機(jī)名請(qǐng)求微服務(wù)贴见。
- 調(diào)用微服務(wù)
@RestController
public class Controller {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/hello")
public String hello() {
return this.restTemplate.getForObject("http://eureka-client-demo/hello", String.class);
}
}
在這里,我們調(diào)用eureka-client-demo服務(wù)的/hello接口時(shí)躲株,直接使用了它的虛擬主機(jī)名片部,Ribbon會(huì)自動(dòng)將虛擬主機(jī)名映射為微服務(wù)的網(wǎng)絡(luò)地址。
參考:《Spring Cloud與Docker微服務(wù)架構(gòu)實(shí)戰(zhàn)》周立 著