一、ribbon簡介
Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies.
—–摘自官網
ribbon是一個負載均衡客戶端,可以很好的控制htt和tcp的一些行爲。Feign默認集成了ribbon。
ribbon 已經默認實現了這些配置bean:
-
IClientConfig ribbonClientConfig: DefaultClientConfigImpl
-
IRule ribbonRule: ZoneAvoidanceRule
-
IPing ribbonPing: NoOpPing
-
ServerList ribbonServerList: ConfigurationBasedServerList
-
ServerListFilter ribbonServerListFilter: ZonePreferenceServerListFilter
-
ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer
二、簡單測試
創建SpringBoot工程,啓動eureka-server 工程;啓動service-hi工程,它的端口爲8762;將service-hi的配置文件的端口改爲8763,並啓動,這時你會發現:service-hi在eureka-server註冊了2個實例,這就相當於一個小的集羣。訪問localhost:8761如圖所示:
重新新建一個spring-boot工程,取名爲:service-ribbon
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: service-ribbon
在工程的啓動類中,通過@EnableDiscoveryClient向服務中心註冊;並且向程序的ioc注入一個bean: restTemplate;並通過@LoadBalanced註解表明這個restRemplate開啓負載均衡的功能。
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
寫一個測試類測試:
在瀏覽器上多次訪問http://localhost:8764/hi?name=forezp,瀏覽器交替顯示:
hi,i am from port:8762
hi,i am from port:8763
這說明當我們通過調用restTemplate.getForObject(“http://SERVICE-HI/hi?name=”+name,String.class)方法時,已經做了負載均衡,訪問了不同的端口的服務實例。
四、此時的架構
- 一個服務註冊中心,eureka server,端口爲8761
- service-hi工程跑了兩個實例,端口分別爲8762,8763,分別向服務註冊中心註冊
- sercvice-ribbon端口爲8764,向服務註冊中心註冊
- 當sercvice-ribbon通過restTemplate調用service-hi的hi接口時,因爲用ribbon進行了負載均衡,會輪流的調用service-hi:8762和8763 兩個端口的hi接口