Hystrix主要用于实现微服务体系中断路器的作用。往往与spring cloud集成使用。但绝大部分的项目现在还没有完全移植到spring cloud环境中。所以了解其独立使用的方式也很必要,好在Netflix出品,必属精品。开发过程中使用起来也比较简便。
以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;@Configurationpublic 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,用于收集监控信息。
被Hystrix监控类
@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进行业务访问。另外可以通过http://主机/项目名/hystrix.stream查看调用事件。由于hystrix.stream以json格式输出,可读性较差,所以需要其他方案以便更优雅的展示监控结果。
https://github.com/kennedyoliveira/standalone-hystrix-dashboard就是一个非常不错的项目,将hystrix.stream产生的json以图形化的形式展现。
在git下载该项目并运行后,配置监控url地址即可直观的查看被@HystrixCommand作用调用情况。
作者:SamHxm
链接:https://www.jianshu.com/p/9641cd888b9a
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦