1. 程式人生 > >netflix-hystrix-簡例

netflix-hystrix-簡例

err man value nbsp together IE efault boa monit

 1 /**
 2  * CommandWithFallbackViaNetwork.run模擬遠程調用失敗,FallbackViaNetwork模擬需要通過網絡從Redis獲取老數據
 3  */
 4 public class CommandWithFallbackViaNetwork extends HystrixCommand<String> {
 5     private final int id;
 6 
 7     protected CommandWithFallbackViaNetwork(int id) {
 8         //不設置ThreadPoolKey時,ThreadPoolKey默認為groupKey,不同的threadPoolKey代表不同的線程池。
9 //A group name for a HystrixCommand. This is used for grouping together commands such as for reporting, alerting, dashboards or team/library ownership. 10 super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX")) 11 //A key to represent a HystrixCommand for monitoring, circuit-breakers, metrics publishing, caching and other such uses.
12 .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueCommand")) 13 .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() 14 .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD))); 15 this
.id = id; 16 } 17 18 @Override 19 protected String run() { 20 // remoteServiceXClient.getValue(id); 21 //模擬遠程調用失敗 22 throw new RuntimeException("force failure for example"); 23 } 24 25 @Override 26 protected String getFallback() { 27 return new FallbackViaNetwork(id).execute(); 28 } 29 30 private static class FallbackViaNetwork extends HystrixCommand<String> { 31 private final int id; 32 private static Map<Integer, String> memCacheClient = new ConcurrentHashMap<>();//充當Redis緩存,需要訪問網絡 33 34 public FallbackViaNetwork(int id) { 35 //groupKey與CommandWithFallbackViaNetwork一致, 36 super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX")) 37 .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueFallbackCommand")) 38 // use a different threadpool for the fallback command 39 // so saturating the RemoteServiceX pool won‘t prevent 40 // fallbacks from executing 41 .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RemoteServiceXFallback"))); 42 this.id = id; 43 } 44 45 @Override 46 protected String run() { 47 return memCacheClient.get(id); 48 } 49 50 @Override 51 protected String getFallback() { 52 // the fallback also failed 53 // so this fallback-of-a-fallback will 54 // fail silently and return null 55 return null; 56 } 57 } 58 }

netflix-hystrix-簡例