java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot+feign+Hystrix

springboot+feign+Hystrix整合(亲测有效)

作者:大树叶

本文主要介绍了springboot+feign+Hystrix整合,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
<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>
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

注意使用@EnableHystrix 和@EnableFeignClients

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

业务代码

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

好了,到此结束,亲自有效!更多相关springboot+feign+Hystrix内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文