一 配置超时时间
1 新建TimeoutCommand
package org.crazyit.cloud.config;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
public class TimeoutCommand extends HystrixCommand<String> {
//设置超时时间为2秒
public TimeoutCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(2000)));
}
@Override
protected String run() throws Exception {
Thread.sleep(3000);
System.out.println("执行命令");
return "success";
}
@Override
protected String getFallback() {
System.out.println("执行回退方法");
return "fallback";
}
}
2 新建测试类
package org.crazyit.cloud.config;
import com.netflix.config.ConfigurationManager;
public class TimeoutMain {
public static void main(String[] args) {
TimeoutCommand c = new TimeoutCommand();
String result = c.execute();
System.out.println(result);
}
}
3 测试结果
执行回退方法
fallback
二 全局配置
1 代码
package org.crazyit.cloud.config;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
public class PropertyMain {
public static void main(String[] args) {
//全局配置
ConfigurationManager
.getConfigInstance()
.setProperty(
"hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds",
2000);
PropertyCommand c = new PropertyCommand();
String result = c.execute();
System.out.println(result);
}
static class PropertyCommand extends HystrixCommand<String> {
public PropertyCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")));
}
@Override
protected String run() throws Exception {
Thread.sleep(3500);
return "success";
}
@Override
protected String getFallback() {
return "fallback";
}
}
}
2 测试结果
fallback
三 配置key
package org.crazyit.cloud.config;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixThreadPoolKey;
public class KeyCommand extends HystrixCommand<String> {
public KeyCommand() {
super(
Setter.withGroupKey(
HystrixCommandGroupKey.Factory.asKey("TestGroupKey"))
.andCommandKey(HystrixCommandKey.Factory.asKey("CommandKey"))
.andThreadPoolKey(
HystrixThreadPoolKey.Factory.asKey("PoolKey")));
}
@Override
protected String run() throws Exception {
// TODO Auto-generated method stub
return null;
}
}