spring boot + feign + Hystrix 整合 (亲测有效)

spring boot + feign + Hystrix 整合,步骤如下:

  1. pom依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>3.0.6</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
     <version> 2.2.10.RELEASE</version>
</dependency>
  1. properties 开启选项
feign:
  client:
    config:
       default:
         #发起重试的时间间隔3s
         feignPeriod: 3000
         #发起重试的最大时间间隔10s,单位毫秒
         feignMaxPeriod: 10000
         #重试次数2,如果需要重试1次,就设置为2
         feignMaxAttempts: 3
         #5s connectTimeout 和 readTimeout 必须同时配置
         connectTimeout: 5000
         readTimeout: 5000
         writeTimeout: 5000
  compression:
    request:
      enabled: true
    response:
      enabled: true
  httpclient:
    enabled: false
  okhttp:
    enabled: true
  circuitbreaker:
    enabled: true

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 5000

注:这里开启选项为feign.circuitbreaker.enable=true,这是对2021年后的spring cloud版本的。 Spring Cloud CircuitBreaker 已经是独立项目了。 springcloud早期版本用下面这段配置在feign中生效:feign.hystrix.enabled=true

  1. Java code example

注意使用@EnableHystrix 和@EnableFeignClients

@EnableTransactionManagement
@EnableAspectJAutoProxy
@Configuration
@SpringBootApplication(scanBasePackages = {"cn.com.datang.test"},exclude = {ArchaiusAutoConfiguration.class})
@EnableCaching
@EnableFeignClients(basePackages = "cn.com.datang.test.rpc")
@EnableHystrix
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

业务代码

@FeignClient(
        name = "mytestapi",
        url = "${datang.mytestapi.addr}",
        fallbackFactory = TestApiFallbackFactory.class
)
public interface TestApi {
    @GetMapping(value = "/testapi")
    String getPersonInfo(@RequestParam(value = "appid") String appid,
                                 @RequestParam(value = "type") String type,
                                 @RequestParam(value = "id") String id);
}
@Slf4j
@Component
public class TestApiFallbackFactory implements FallbackFactory<TestApi> {
    @Override
    public TestApi create(Throwable cause) {
        return (appid, type, id) -> {
             log.warn("网络调用异常,使用降级措施来处理了.异常信息:",cause);
             return null;
         };
    }
}

好了,到此结束,亲自有效!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值