Hystrix主要用于實現微服務體系中斷路器的作用。往往與spring cloud集成使用。但絕大部分的項目現在還沒有完全移植到spring cloud環(huán)境中。所以了解其獨立使用的方式也很必要,好在Netflix出品,必屬精品。開發(fā)過程中使用起來也比較簡便。
以spring boot項目加入Hystrix為例,看看如果快速的項目中使用Hystrix特性。
maven依賴
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-metrics-event-stream</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>1.5.9</version>
</dependency>
spring boot配置類
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
@Configuration
public class HystrixConfiguration {
@Bean
public HystrixCommandAspect hystrixAspect() {
return new HystrixCommandAspect();
}
@Bean
public ServletRegistrationBean hystrixMetricsStreamServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
registration.addUrlMappings("/hystrix.stream");
return registration;
}
}
聲明一個HystrixCommandAspect代理類,用于以后被Hystrix相關注解的切面。另外聲明一個Servlet,用于收集監(jiān)控信息。
被Hystrix監(jiān)控類
@RestController
@RequestMapping({ "/test" })
public class UserController {
@Autowired
private RemoteService remoteService;
@RequestMapping(value = "/user")
@HystrixCommand(fallbackMethod = "fallback", threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "30"), @HystrixProperty(name = "maxQueueSize", value = "100"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "20") }, commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "1")
})
public User getUser1() throws InterruptedException{
User user = remoteService.getUser1();
return user;
}
public User fallback(Throwable e) {
e.printStackTrace();
return new User();
}
}
通過@HystrixCommand設定斷路策略,各配置具體作用參考官方解釋。
項目運行之后可以通過http://主機/項目名/test/user進行業(yè)務訪問。另外可以通過http://主機/項目名/hystrix.stream查看調用事件。由于hystrix.stream以json格式輸出,可讀性較差,所以需要其他方案以便更優(yōu)雅的展示監(jiān)控結果。
https://github.com/kennedyoliveira/standalone-hystrix-dashboard就是一個非常不錯的項目,將hystrix.stream產生的json以圖形化的形式展現。
在git下載該項目并運行后,配置監(jiān)控url地址即可直觀的查看被@HystrixCommand作用調用情況。