Ribbon簡(jiǎn)介
在微服務(wù)架構(gòu)中,業(yè)務(wù)都會(huì)被拆分成一個(gè)獨(dú)立的服務(wù),服務(wù)與服務(wù)的通訊是基于Http Restful的。SpringCloud有兩種服務(wù)調(diào)用方式,一種是Ribbon + RestTemplate,另一種是Feign。Ribbon是一個(gè)負(fù)載均衡客戶端,可以很好的控制http和tcp的一些行為。Feign默認(rèn)集成了Ribbon。
- 引入依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
- 通過@EnableDiscoveryClient向服務(wù)中心注冊(cè):
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
向程序的ioc注入一個(gè)bean: restTemplate;并通過@LoadBalanced注解表明這個(gè)restRemplate開啟負(fù)載均衡的功能。
- 配置文件application.yml如下:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: service-ribbon
啟動(dòng)工程后,可以在 http://localhost:8761/ 中看到service-ribbon注冊(cè)進(jìn)來了。
負(fù)載均衡測(cè)試:
- 復(fù)制一個(gè)上篇文章中端口為8762的微服務(wù)service-1,將端口改為8763啟動(dòng),此時(shí)可以在注冊(cè)表中看到有兩個(gè)service-1實(shí)例。
- 接下來通過之前注入IOC容器的restTemplate來消費(fèi)service-1服務(wù)的接口,我們可以用的程序名替代具體的URL地址,在Ribbon中會(huì)根據(jù)服務(wù)名來選擇具體的服務(wù)實(shí)例,根據(jù)服務(wù)實(shí)例在請(qǐng)求的時(shí)候會(huì)用具體的url替換掉服務(wù)名。
- 在瀏覽器上多次訪問
http://localhost:8764/{yourInterface}
就會(huì)出現(xiàn)啟動(dòng)的兩個(gè)service-1實(shí)例會(huì)被輪流調(diào)用,這就說明進(jìn)行了負(fù)載均衡,訪問了不同的端口的服務(wù)實(shí)例。