netflix-hystrix-简例

 
 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 }
 

相关内容推荐