原创

springcloud2集成hystrix及HystrixDashbord

温馨提示:
本文最后更新于 2019年09月22日,已超过 1,640 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

首先业务服务需要引入hystrix的jar,同时,hystrix依赖actuator,所以,这两个都需要引入,pom.xml配置如下:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

因为使用parent,所以这里没有定义版本号,请自行定义。

jar包依赖导入之后,需要在配置文件中增加如下配置:

# 加载所有的端点/默认只加载了 info / health
management:
endpoints:
web:
exposure:
include: "*"
jmx:
exposure:
include: "*"
endpoint:
health:
show-details: always
enabled: true
hystrix:
stream:
enabled: true

feign:
hystrix:
enabled: true


需要注意的是,仅仅引入jar并增加配置,还是不够的,有时候我们增加了HystrixDashbord,但是监控中一直没有数据,是因为我们调用的接口并没有做熔断处理。代码样例如下:

@FeignClient(value = "goods",fallback = GoodsClientFeignHystrix.class)
public interface GoodsClient {

/**
* 获取已上架的商品
* @param channelId
* @param shopId
* @return
*/
@GetMapping(value = "/test")
HystrixCommand<Set<String>> getShelfGoodsIdByShopId(@PathVariable("channelId") Integer channelId,
@PathVariable("shopId")String shopId);

}

我们需要在接口上增加fallback的实现类,实现类内容如下:

@Component
@Slf4j
public class GoodsClientFeignHystrix implements GoodsClient {

private static final Setter hystrixCommandGroupKey =
Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("UserApi"));


@Override
public HystrixCommand<Set<String>> getShelfGoodsIdByShopId(Integer channelId, String shopId) {
return new HystrixCommand<Set<String>>(hystrixCommandGroupKey) {
@Override
protected Set<String> run() throws Exception {
log.error("调用失败");
return null;
}
};
}
}

调用这样的接口才会有数据。

启动服务,假设端口设置为8023,访问地址为:http://localhost:8023/actuator/hystrix.stream 则在没有调用该接口的时候,输入如下:

在请求该接口后,页面输入内容如下:

这样,说明我们的服务和接口熔断都是可用的了。

然后再创建一个工程,pom.xml添加如下配置:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

spring boot启动类上面加入注解EnableHystrixDashboard

@SpringBootApplication
@EnableHystrixDashboard
public class AppHystrixDashbord {
public static void main(String[] args) {
SpringApplication.run(AppHystrixDashbord.class);
} }

启动项目后访问/hystrix能看见一个类似tomcat的首页

 

在中间这个输入框中,填入需要监控的微服务的监控地址 也就是/actuator/hystrix.stream点击按钮,就会跳转到 仪表盘页面:

 


Hystrix仪表盘解释: 

实心圆:共有两种含义。它通过颜色的变化代表了实例的健康程度,它的健康度从绿色。该实心圆除了颜色的变化之外,它的大小也会根据实例的请求流量发生变化,流量越大该实心圆就越大。所以通过

该实心圆的展示,就可以在大量的实例中快速的发现故障实例和高压力实例。曲线:用来记录2分钟内流量的相对变化,可以通过它来观察到流量的上升和下降趋势。 整图解释:

 

正文到此结束
本文目录