Spring Cloud搭建手册(5)——Spring Cloud Feign

1、在POM文件添加依赖:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

2、在Spring boot入口类添加注解:

@EnableFeignClients

3、创建一个客户端接口,该接口的方法使用Spring MVC注解绑定提供实际服务的接口,使用@FeignClient注解指定服务名绑定服务:

@FeignClient("hello-service")
public interface HelloClient {

@GetMapping("/hello")
public String hello();

@PostMapping("/hello/{who}")
public String helloWho(@PathVariable("who") String who);
}

4、为服务添加超时和重试功能,hello-service为注册的服务名,如果不加服务名前缀,则是全局设置:

hello-service.ribbon.ConnectTimeout=500
hello-service.ribbon.ReadTimeout=2000
hello-service.ribbon.OkToRetryOnAllOperations=true
hello-service.ribbon.MaxAutoRetriesNextServer=1
hello-service.ribbon.MaxAutoRetries=0

5、使用Hystrix对服务做容错保护,首先需要开启Feign中的Hystrix开关:

feign.hystrix.enabled=true

6、在Spring Boot入口类添加启用断路器的注解:

@EnableCircuitBreaker

设置Hystrix的全局超时时间,到达该超时时间会引起熔断,所以需要这个超时时间大于Ribbon的超时时间,不然Hystrix先超时了,Ribbon的重试机制无法起到效果:

hystrix.command.default.execution.timeout.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000

6、使用Hystrix实现服务降级,首先先需要定义一个服务降级类,来实现前面HelloClient的方法:

@Component
public class HelloClientFallback implements HelloClient {

    @Override
    public String hello() {
        return "error";
    }

    @Override
    public String helloWho(String who) {
        return "error";
    }
}

之后,在服务绑定接口HelloClient中,通过@FeignClient注解的fallback属性来指定对应的服务降级实现类,原来的注解改成以下形式:

@FeignClient(name = "hello-service", fallback = HelloClientFallback.class)

7、可能遇到的问题:

① Method xxx not annotated with HTTP method type (ex. GET, POST)

101557_juig_1445585.png

原因:在老版本的Feign使用中,不能使用@GetMapping("/xxx")方式声明。Dalston版本已支持。

解决办法:改成@RequestMapping(value = "/xxx", method = RequestMethod.GET)。

② PathVariable annotation was empty on param 0.

101752_WoyB_1445585.png

原因:未在@PathVariable注解中指定value。

解决办法:指定@PathVariable注解的value,例如@PathVariable(“id”)。

转载于:https://my.oschina.net/u/1445585/blog/1621936

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值