Spring Cloud實(shí)戰(zhàn)小貼士:Ribbon的饑餓加載(eager-load)模式
我們在使用Spring Cloud的Ribbon或Feign來實(shí)現(xiàn)服務(wù)調(diào)用的時候,如果我們的機(jī)器或網(wǎng)絡(luò)環(huán)境等原因不是很好的話,有時候會發(fā)現(xiàn)這樣一個問題:我們服務(wù)消費(fèi)方調(diào)用服務(wù)提供方接口的時候,***次請求經(jīng)常會超時,而之后的調(diào)用就沒有問題了。下面我們就來說說造成這個問題的原因,以及如何解決的方法。
問題原因
造成***次服務(wù)調(diào)用出現(xiàn)失敗的原因主要是Ribbon進(jìn)行客戶端負(fù)載均衡的Client并不是在服務(wù)啟動的時候就初始化好的,而是在調(diào)用的時候才會去創(chuàng)建相應(yīng)的Client,所以***次調(diào)用的耗時不僅僅包含發(fā)送HTTP請求的時間,還包含了創(chuàng)建RibbonClient的時間,這樣一來如果創(chuàng)建時間速度較慢,同時設(shè)置的超時時間又比較短的話,很容易就會出現(xiàn)上面所描述的顯現(xiàn)。
從日志中我們也能知道這一點(diǎn)細(xì)節(jié),在***次發(fā)起調(diào)用的時候我們可以從日志中看到如下信息:
- 2017-09-25 08:29:54,201 INFO [main] com.netflix.loadbalancer.DynamicServerListLoadBalancer - DynamicServerListLoadBalancer for client hello-service initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=hello-service,current list of Servers=[192.168.99.176:9901],Load balancer stats=Zone stats: {unknown=[Zone:unknown; Instance count:1; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
- },Server stats: [[Server:192.168.99.176:9901; Zone:UNKNOWN; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
- ]}ServerList:ConsulServerList{serviceId='hello-service', tag=null}
而Feign的實(shí)現(xiàn)基于Ribbon,所以它也有一樣的問題,下面就來看看如何解決這個問題。
解決方法
解決的方法很簡單,既然***次調(diào)用時候產(chǎn)生RibbonClient耗時,那么就讓它提前創(chuàng)建,而不是在***次調(diào)用的時候創(chuàng)建。
在Spring Cloud的Dlaston版本中提供了幾個新的參數(shù),它們可以很方便的幫我們實(shí)現(xiàn)這樣的功能。
- ribbon.eager-load.enabled=true
- ribbon.eager-load.clients=hello-service, user-service
參數(shù)說明:
- ribbon.eager-load.enabled:開啟Ribbon的饑餓加載模式
- ribbon.eager-load.clients:指定需要饑餓加載的客戶端名稱、服務(wù)名
通過上面的配置完成之后,我們嘗試重啟一下服務(wù)消費(fèi)者,這個時候我們會發(fā)現(xiàn),我們沒有開始調(diào)用服務(wù)接口,但是上面初始化負(fù)載均衡的日志就已經(jīng)打印出來了。這就說明我們對ribbon的饑餓加載模塊設(shè)置已經(jīng)生效了。
【本文為51CTO專欄作者“翟永超”的原創(chuàng)稿件,轉(zhuǎn)載請通過51CTO聯(lián)系作者獲取授權(quán)】