Spring Cloud应用开发(四:服务容错保护)

1、Spring Cloud Hystrix的使用

1.1、创建microservice-eureka-user-hystrix工程,并在其pom.xml中引入eureka和hystrix的依赖;

Spring Cloud应用开发(四:服务容错保护)

 

1.2、编写配置文件。在配置文件中添加Eureka服务实例的端口号,服务端地址等;

Spring Cloud应用开发(四:服务容错保护)

 

1.3、在工程主类Application中使用@EnableCircuitBreaker注解开启断路器功能;

Spring Cloud应用开发(四:服务容错保护)

1.4、修改用户控制器类。在findOrderByUser()方法上添加@HystrixCommand注解来指定回调方法;

Spring Cloud应用开发(四:服务容错保护)

 

1.5、分别启动注册中心,服务提供者(7900和7901)和服务消费者后,注册中心信息页面中已注册的服务如下图。

Spring Cloud应用开发(四:服务容错保护)

 

1.6、关闭7901对应的服务,访问页面如下图;

Spring Cloud应用开发(四:服务容错保护)

Spring Cloud应用开发(四:服务容错保护)

2、Spring Cloud Hystrix Dashboard的使用

2.1、在配置文件pom.xml中添加相关的监控依赖;

Spring Cloud应用开发(四:服务容错保护)

2.2、分别启动注册中心,服务提供者(7900)和服务消费者后,访问地址http://localhost:8030/findOrdersByUser/1(此步骤不可省略,否则将由于系统应用的所有接口都未被调用而只输出ping:);

2.3、通过浏览器访问地址http://localhost:8030/hystrix.stream,如下图所示。

Spring Cloud应用开发(四:服务容错保护)

3、创建可视化上查看实时数据监控;

3.1、新建ms-spring-cloud的子工程ms-hystrix-dashnard。在配置文件pom.xml中添加相关的监控依赖;

Spring Cloud应用开发(四:服务容错保护)

3.2、编写配置文件application.yml,指定应用的端口号和名称等信息。

Spring Cloud应用开发(四:服务容错保护)

3.3、编写启动类Application.java,并在其类上添加@EnableHystrixDashboard注解来开启Hystrix仪表盘功能。

Spring Cloud应用开发(四:服务容错保护)

3.4、启动工程,访问地址http://localhost:8031/hystrix.stream如下图所示;

Spring Cloud应用开发(四:服务容错保护)

3.5、设置Title为”订单微服务”,并点击[Monitor Stream]按钮;

Spring Cloud应用开发(四:服务容错保护)

3.6、通过浏览器访问http://localhost:8030/findOrdersByUser/1,并不断刷新操作;

Spring Cloud应用开发(四:服务容错保护)