使用Hystrix守护应用(1)

Hystrix(https://github.com/Netflix/Hystrix)是Netflix(https://www.netflix.com/global)的一个开源项目,主要作用是通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。 其可以看做是Netflix团队对分布式系统运维的各种理念和实践的总结。值得一提的是在ThoughtWorks最新的Tech Radar 2014(http://www.thoughtworks.com/radar/#/tools)中,Hystrix的评级已从评估(Assess)上升到试用(Trial),即其已经完善到可以在产品环境中试用了,相信会有越来越多的公司采用该类库来提升自己系统的容错能力,我所在的部门刚刚把Hystrix加入了工具箱,并已在某几个项目中实践了Hystrix。 

在项目中使用Hystrix 
Hystrix本质上是一个基于JVM的类库,Netflix团队已经把其发布到Maven中央库中,因此只要你的项目是基于JVM的,那么在项目中使用Hystrix就非常容易了。本文中将以Gradle为构建脚本的Spring MVC Web项目为例(代码已托管到github:https://github.com/xianlinbox/HystrixDemo),在该示例项目中,构建了一个Customer Service,该customer service会依赖另外的2个web service(Contact Service和Address Service, 示例中我使用moco(https://github.com/dreamhead/moco)模拟了这2个服务)。如下图: 
使用Hystrix守护应用(1)_第1张图片
在Customer Service模块中使用Hystrix把对Contact Service和Address Service的依赖隔离开,可以防止一个服务的故障影响到另外一个服务。 

首先,为项目添加Hystrix依赖: 

Gradle代码  收藏代码

  1. 'com.netflix.hystrix:hystrix-core:1.3.8',  


然后,把所有需要访问远程系统,服务和第三方库的调用都封装到HystrixCommand中, 

Java代码  收藏代码

  1. public class AddressHystrixCommand extends HystrixCommand<Address> {  

  2.     private Logger logger = LoggerFactory.getLogger(AddressHystrixCommand.class);  

  3.     private String customerId;  

  4.   

  5.     public AddressHystrixCommand(String customerId) {  

  6.         super(HystrixCommandGroupKey.Factory.asKey("Address"));  

  7.         this.customerId = customerId;  

  8.     }  

  9.   

  10.     @Override  

  11.     public Address run() throws Exception {  

  12.         logger.info("Get address for customer {}", customerId);  

  13.         String response = Request.Get("http://localhost:9090/customer/" + customerId + "/address")  

  14.                 .connectTimeout(1000)  

  15.                 .socketTimeout(1000)  

  16.                 .execute()  

  17.                 .returnContent()  

  18.                 .asString();  

  19.   

  20.         return new ObjectMapper().readValue(response, Address.class);  

  21.     }  

  22. }  

  23.   

  24. public class ContactHystrixCommand extends HystrixCommand<Contact> {  

  25.     private Logger logger = LoggerFactory.getLogger(ContactHystrixCommand.class);  

  26.     private String customerId;  

  27.   

  28.     public ContactHystrixCommand(String customerId) {  

  29.         super(HystrixCommandGroupKey.Factory.asKey("Contact"));  

  30.         this.customerId = customerId;  

  31.     }  

  32.   

  33.     @Override  

  34.     public Contact run() throws Exception {  

  35.         logger.info("Get contact for customer {}", customerId);  

  36.         String response = Request.Get("http://localhost:9090/customer/" + customerId + "/contact")  

  37.                 .connectTimeout(1000)  

  38.                 .socketTimeout(1000)  

  39.                 .execute()  

  40.                 .returnContent()  

  41.                 .asString();  

  42.   

  43.         return new ObjectMapper().readValue(response, Contact.class);  

  44.     }  

  45. }  


最后,在需要调用远程服务时候,使用HystrixCommand的方法即可 

Java代码  收藏代码

  1. customer.setContact(new ContactHystrixCommand(customerId).execute());  

  2. customer.setAddress(new AddressHystrixCommand(customerId).execute());  


运行效果如下: 
21:01:11.117 [373380609@qtp-1421210709-0] INFO  c.x.h.s.CustomerService - Get Customer 1234 
21:01:11.163 [373380609@qtp-1421210709-0] WARN  c.n.c.s.URLConfigurationSource - No URLs will be polled as dynamic configuration sources. 
21:01:11.207 [hystrix-Contact-1] INFO  c.x.h.d.ContactHystrixCommand - Get contact for customer 1234 
21:01:11.378 [hystrix-Address-1] INFO  c.x.h.d.AddressHystrixCommand - Get address for customer 1234 

从日志中,我们可以看到HystrixCommand封装的服务分别运行在单独的线程中。上面只是最简单的Hystrix用法,Netflix在Hystrix中加入了非常细致的配置和灵活的使用方法,以帮助用户灵活的得到自己想要的控制效果。下面就来看一看具体有哪些配置和用法。 

配置HystrixCommand 
HystxixCommand支持如下的配置: 
GroupKey:该命令属于哪一个组,可以帮助我们更好的组织命令。 
CommandKey:该命令的名称 
ThreadPoolKey:该命令所属线程池的名称,同样配置的命令会共享同一线程池,若不配置,会默认使用GroupKey作为线程池名称。 
CommandProperties:该命令的一些设置,包括断路器的配置,隔离策略,降级设置,以及一些监控指标等。 
ThreadPoolProerties:关于线程池的配置,包括线程池大小,排队队列的大小等。 

为了方便大家的配置,Hystrix非常贴心的提供了很多工厂方法。下面就是一个涉及到上面所有配置的例子: 

Java代码  收藏代码

  1. public class EchoCommand extends HystrixCommand<String> {  

  2.     private String input;  

  3.   

  4.     protected EchoCommand(String input) {  

  5.         super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("EchoGroup"))  

  6.                 .andCommandKey(HystrixCommandKey.Factory.asKey("Echo"))  

  7.                 .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("EchoThreadPool"))  

  8.                 .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()  

  9.                         .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD))  

  10.                 .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()  

  11.                         .withCoreSize(10))  

  12.         );  

  13.         this.input = input;  

  14.     }  

  15.   

  16.     @Override  

  17.     protected String run() throws Exception {  

  18.         return "Echo: " + input;  

  19.     }     

  20. }  



你可能感兴趣的:(使用Hystrix守护应用(1))