在《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版本只需要注意服务名大小写保持一致即可。