1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| package com.fuyi.hystrix.command;
import java.util.concurrent.TimeUnit;
import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolKey;
public class FallbackCommand extends HystrixCommand<String> {
private final String name; protected FallbackCommand(String name) { super(Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey("userServiceGroup")) .andCommandPropertiesDefaults( // 配置调用依赖超时时间为500,超时后调用降级方法 HystrixCommandProperties.Setter().withExecutionIsolationThreadTimeoutInMilliseconds(500) )); this.name = name; }
@Override protected String run() throws Exception { // 此处睡眠1秒,模拟调用超时,配置超时时间为500毫秒 TimeUnit.MILLISECONDS.sleep(1000); return "Hello " + name +" thread:" + Thread.currentThread().getName(); }
// 超时后调用的降级逻辑方法 @Override protected String getFallback() { return "execute falled"; } public static void main(String[] args) { FallbackCommand c = new FallbackCommand("fuyi"); String result = c.execute(); System.out.println(result); } }
|