SpringCloud(第 014 篇)電影 Ribbon 微服務集成 Hystrix 斷路器實現失敗快速響應,達到熔斷效果
一、大致介紹
1、Hystrix 斷路器的原理很簡單,如同電力過載保護器。它可以實現快速失敗,如果它在一段時間內偵測到許多類似的錯誤,會強迫其以后的多個調用快速失敗,不再訪問遠程服務器,從而防止應用程序不斷地嘗試執行可能會失敗的操作,使得應用程序繼續執行而不用等待修正錯誤,或者浪費CPU時間去等到長時間的超時產生。熔斷器也可以使應用程序能夠診斷錯誤是否已經修正,如果已經修正,應用程序會再次嘗試調用操作;
2、而本章節主要簡單的使用了當下游服務出現宕機或者意外情況不可用時,Hystrix實現了快速失敗快速響應來達到熔斷機制效果;
二、實現步驟
2.1 添加 maven 引用包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>springms-consumer-movie-ribbon-with-hystrix</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.springms.cloud</groupId>
<artifactId>springms-spring-cloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- web模塊 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 客戶端發現模塊 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- Hystrix 斷路器模塊 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<!-- 監控和管理生產環境的模塊 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
2.2 添加應用配置文件(springms-consumer-movie-ribbon-with-hystrix\src\main\resources\application.yml)
spring:
application:
name: springms-consumer-movie-ribbon-with-hystrix
server:
port: 8070
#做負載均衡的時候,不需要這個動態配置的地址
#user:
# userServicePath: http://localhost:7900/simple/
eureka:
client:
# healthcheck:
# enabled: true
serviceUrl:
defaultZone: http://admin:admin@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
# 解決第一次請求報超時異常的方案,因為 hystrix 的默認超時時間是 1 秒,因此請求超過該時間后,就會出現頁面超時顯示 :
#
# 這里就介紹大概三種方式來解決超時的問題,解決方案如下:
#
# 第一種方式:將 hystrix 的超時時間設置成 5000 毫秒
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
#
# 或者:
# 第二種方式:將 hystrix 的超時時間直接禁用掉,這樣就沒有超時的一說了,因為永遠也不會超時了
# hystrix.command.default.execution.timeout.enabled: false
#
# 或者:
# 第三種方式:索性禁用feign的hystrix支持
# feign.hystrix.enabled: false ## 索性禁用feign的hystrix支持
# 超時的issue:https://github.com/spring-cloud/spring-cloud-netflix/issues/768
# 超時的解決方案: http://stackoverflow.com/questions/27375557/hystrix-command-fails-with-timed-out-and-no-fallback-available
# hystrix配置: https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.thread.timeoutInMilliseconds
2.3 添加實體用戶類User(springms-consumer-movie-ribbon-with-hystrix\src\main\java\com\springms\cloud\entity\User.java)
package com.springms.cloud.entity;
import java.math.BigDecimal;
public class User {
private Long id;
private String username;
private String name;
private Short age;
private BigDecimal balance;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Short getAge() {
return this.age;
}
public void setAge(Short age) {
this.age = age;
}
public BigDecimal getBalance() {
return this.balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
2.4 添加電影Web訪問層Controller(springms-consumer-movie-ribbon-with-hystrix\src\main\java\com\springms\cloud\controller\MovieRibbonHystrixController.java)
package com.springms.cloud.controller;
import com.springms.cloud.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Web控制器測試斷路器功能。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/21
*
*/
@RestController
public class MovieRibbonHystrixController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
@HystrixCommand(fallbackMethod = "findByIdFallback")
public User findById(@PathVariable Long id) {
// http://localhost:7900/simple/
// VIP:virtual IP
// HAProxy Heartbeat
return this.restTemplate.getForObject("http://springms-provider-user/simple/" + id, User.class);
}
/**
* 當 springms-provider-user 服務宕機或者不可用時,即請求超時后會調用此方法。
*
* @param id
* @return
*/
public User findByIdFallback(Long id) {
User user = new User();
user.setId(0L);
return user;
}
}
2.5 添加電影微服務啟動類(springms-consumer-movie-ribbon-with-hystrix\src\main\java\com\springms\cloud\MsConsumerMovieRibbonHystrixApplication.java)
package com.springms.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* 電影 Ribbon 微服務集成 Hystrix 斷路器實現失敗快速響應,達到熔斷效果。
*
* 注解 EnableCircuitBreaker 表明需要集成斷路器模塊;
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/21
*
*/
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class MsConsumerMovieRibbonHystrixApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(MsConsumerMovieRibbonHystrixApplication.class, args);
System.out.println("【【【【【【 電影微服務-Hystrix 】】】】】】已啟動.");
}
}
三、測試
/****************************************************************************************
一、電影 Ribbon 微服務集成 Hystrix 斷路器實現失敗快速響應,達到熔斷效果:
1、注解:EnableCircuitBreaker、HystrixCommand 的編寫;
2、啟動 springms-provider-user 模塊服務,啟動1個端口;
3、啟動 springms-consumer-movie-ribbon-with-hystrix 模塊服務;
4、在瀏覽器輸入地址http://localhost:8070/movie/1,然后頁面的信息是否有打印出來用戶的Id=0的情況,正常情況下是沒有用戶Id=0的情況信息打印的;
5、殺死 springms-provider-user 模塊服務,停止提供服務;
6、在瀏覽器輸入地址http://localhost:8070/movie/1,然后頁面的信息是否有打印出來用戶的Id=0的情況,等了1秒中后有用戶Id=0的情況信息打印出來;
7、等一會兒在啟動 springms-provider-user 模塊服務,啟動1個端口;
8、在瀏覽器輸入地址http://localhost:8070/movie/1,然后頁面的信息又有Id!=0的用戶信息打印出來;
總結:當遠端微服務宕機或者不可用時,Hystrix已經達到快速響應快速失敗,起到了熔斷機制的效果。
****************************************************************************************/
四、下載地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群: 235322432
SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接
歡迎關注,您的肯定是對我最大的支持!!!