- 引入Hystrix依赖
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.18</version>
</dependency>
- 自定义一个Service,加上@Service注解。建议再添加一个@Slf4j注解,用于日志打印
- 创建一个内部类,继承HystrixCommand<响应结果体>
- 具体实现
@Service
@Slf4j
public class HystrixService {
public HystrixResp request(String url, HystrixReq req) {
CommonHystrixCommand commonHystrixCommand = new CommonHystrixCommand(url, req);
HystrixResp resp = commonHystrixCommand.execute();
return resp;
}
private class CommonHystrixCommand extends HystrixCommand<HystrixResp> {
private String url;
private HystrixReq req;
CommonHystrixCommand(String url, HystrixReq req) {
super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("msgRptGroup"))
.andCommandKey(HystrixCommandKey.Factory.asKey("msgRpt"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("msgRptPool"))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withCoreSize(200)
.withMaximumSize(200))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(2000)
.withCircuitBreakerSleepWindowInMilliseconds(5000)
.withCircuitBreakerErrorThresholdPercentage(20)
.withCircuitBreakerRequestVolumeThreshold(10)
.withFallbackIsolationSemaphoreMaxConcurrentRequests(20)));
this.url = url;
this.req = req;
}
@Override
protected HystrixResp run() throws Exception {
HystrixResp resp = HttpClient.post(url, req, HystrixResp.class);
return resp;
}
@Override
protected HystrixResp getFallback() {
log.warn("Hystrix fallback");
PerfCounter.setMeterCount("getFallback", 1L, "reportUrl=" + reportUrl);
HystrixResp resp = new HystrixResp();
resp.setCode(0);
resp.setMsg("fallback");
return resp;
}
}
}