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:
#发起重试的时间间隔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
- Java code example
注意使用@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;
};
}
}
好了,到此结束,亲自有效!