天天看點

關于在Spring Cloud Feign工程中使用Ribbon配置不生效的問題

      在《spring cloud 微服務實戰》第209頁,聲明式服務調用:Spring Cloud Feign---------Ribbon配置這一部分。書上介紹說:由于Spring Cloud Feign的用戶端負載均衡是通過Spring Cloud Ribbon實作的,是以我們可以直接通過配置Ribbon用戶端的方式來自定義各個服務用戶端調用的參數,而針對各個服務用戶端進行個性化配置的方式也采用

<client>.ribbon.key=value的格式進行配置。

     這裡的<client>指的就是服務名,對于這本書上的例子就是hello-service。那麼為什麼你按照那種格式配置了ribbon參數卻不生效呢?先從服務名說起:比如hello-service這個項目ip為localhost,端口為8081,如果沒有服務治理架構,你調用hello-service還得這麼請求:restTemplate.getForObject("http://localhost:8081/hello",String.class,"twst");要不然你得在配置檔案中指定具體的執行個體清單:hello-service.ribbon.listOfServers=localhost:8081;而有了服務治理架構的幫助,你就不需要為用戶端指定具體的執行個體清單,可以指定服務名來做詳細的配置:例如restTemplate.getForObject("http://HELLO-SERVICE/hello",String.class,"twst");

    在使用Spring Cloud Feign時,會在接口上添加@FeignClient("hello-service")注解,并在注解裡指定服務名來綁定服務,書上指出:這裡服務名不區分大小寫。

@FeignClient("hello-service")
public interface HelloService {
    @RequestMapping("/hello")
    String hello();
    @GetMapping(value = "/hello1")
    String hello(@RequestParam("name") String name);
    @GetMapping(value = "/hello2")
    String hello(@RequestHeader("name") String name, @RequestHeader("id") int id);
    @PostMapping(value = "/hello3")
    String hello(@RequestBody User user);
}      

         雖然在這裡@FeignClient("hello-service")服務名大小寫無所謂,但是接下來你要是在application.properties中配置hello-service服務的ribbon參數,那就要注意大小寫了,一定要和你在@FeignClient注解裡的大小寫保持一緻,例如我這裡注解中服務名是小寫的hello-service,那application.properties中也是小寫的:

hello-service.ribbon.ConnectTimeout=500 #請求連接配接逾時時間
hello-service.ribbon.ReadTimeout=1000 #請求處理的逾時時間
hello-service.ribbon.OkToRetryOnAllOperations=true #對所有請求都進行重試
hello-service.ribbon.MaxAutoRetriesNextServer=2 #切換執行個體的重試次數
hello-service.ribbon.MaxAutoRetries=1 #對目前執行個體的重試次數      

       因為書上内容不嚴謹,一會大寫,一會小寫,我剛開始有沒生效,還以為是重試機制沒開啟(spring.cloud.loadbalancer.retry.enabled=true),其實從Camden SR2版本開始就已經預設是開啟狀态,而我用的是Dalston版本,是以根本不是這個原因,作者部落格上評論區也有人詢問怎麼不生效,作者并沒回複,有熱心網友說要引入spring-retry依賴,估計他用的是低版本的吧,反正Dalston版本隻需要注意服務名大小寫保持一緻即可。