spring boot + feign + Hystrix 整合,步骤如下:
- 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>
- properties 开启选项
feign:client:config:default:#发起重试的时间间隔3sfeignPeriod: 3000#发起重试的最大时间间隔10s,单位毫秒feignMaxPeriod: 10000#重试次数2,如果需要重试1次,就设置为2feignMaxAttempts: 3#5s connectTimeout 和 readTimeout 必须同时配置connectTimeout: 5000readTimeout: 5000writeTimeout: 5000compression:request:enabled: trueresponse:enabled: truehttpclient:enabled: falseokhttp:enabled: truecircuitbreaker:enabled: truehystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 5000
注:这里开启选项为feign.circuitbreaker.enable=true,这是对2021年后的spring cloud版本的。 Spring Cloud CircuitBreaker 已经是独立项目了。 springcloud早期版本用下面这段配置在feign中生效:feign.hystrix.enabled=true
- 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> {@Overridepublic TestApi create(Throwable cause) {return (appid, type, id) -> {log.warn("网络调用异常,使用降级措施来处理了.异常信息:",cause);return null;};}
}
好了,到此结束,亲自有效!