SpringCloud(第 014 篇)電影 Ribbon 微服務(wù)集成 Hystrix 斷路器實(shí)現(xiàn)失敗快速響應(yīng)显熏,達(dá)到熔斷效果
一雄嚣、大致介紹
1、Hystrix 斷路器的原理很簡(jiǎn)單喘蟆,如同電力過載保護(hù)器缓升。它可以實(shí)現(xiàn)快速失敗,如果它在一段時(shí)間內(nèi)偵測(cè)到許多類似的錯(cuò)誤蕴轨,會(huì)強(qiáng)迫其以后的多個(gè)調(diào)用快速失敗港谊,不再訪問遠(yuǎn)程服務(wù)器,從而防止應(yīng)用程序不斷地嘗試執(zhí)行可能會(huì)失敗的操作橙弱,使得應(yīng)用程序繼續(xù)執(zhí)行而不用等待修正錯(cuò)誤歧寺,或者浪費(fèi)CPU時(shí)間去等到長(zhǎng)時(shí)間的超時(shí)產(chǎn)生燥狰。熔斷器也可以使應(yīng)用程序能夠診斷錯(cuò)誤是否已經(jīng)修正,如果已經(jīng)修正斜筐,應(yīng)用程序會(huì)再次嘗試調(diào)用操作龙致;
2、而本章節(jié)主要簡(jiǎn)單的使用了當(dāng)下游服務(wù)出現(xiàn)宕機(jī)或者意外情況不可用時(shí)顷链,Hystrix實(shí)現(xiàn)了快速失敗快速響應(yīng)來達(dá)到熔斷機(jī)制效果目代;
二、實(shí)現(xiàn)步驟
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>
<!-- 客戶端發(fā)現(xiàn)模塊 -->
<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>
<!-- 監(jiān)控和管理生產(chǎn)環(huán)境的模塊 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
2.2 添加應(yīng)用配置文件(springms-consumer-movie-ribbon-with-hystrix\src\main\resources\application.yml)
spring:
application:
name: springms-consumer-movie-ribbon-with-hystrix
server:
port: 8070
#做負(fù)載均衡的時(shí)候嗤练,不需要這個(gè)動(dòng)態(tài)配置的地址
#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}}
# 解決第一次請(qǐng)求報(bào)超時(shí)異常的方案榛了,因?yàn)?hystrix 的默認(rèn)超時(shí)時(shí)間是 1 秒,因此請(qǐng)求超過該時(shí)間后煞抬,就會(huì)出現(xiàn)頁(yè)面超時(shí)顯示 :
#
# 這里就介紹大概三種方式來解決超時(shí)的問題忽冻,解決方案如下:
#
# 第一種方式:將 hystrix 的超時(shí)時(shí)間設(shè)置成 5000 毫秒
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
#
# 或者:
# 第二種方式:將 hystrix 的超時(shí)時(shí)間直接禁用掉,這樣就沒有超時(shí)的一說了此疹,因?yàn)橛肋h(yuǎn)也不會(huì)超時(shí)了
# hystrix.command.default.execution.timeout.enabled: false
#
# 或者:
# 第三種方式:索性禁用feign的hystrix支持
# feign.hystrix.enabled: false ## 索性禁用feign的hystrix支持
# 超時(shí)的issue:https://github.com/spring-cloud/spring-cloud-netflix/issues/768
# 超時(shí)的解決方案: 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 添加實(shí)體用戶類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控制器測(cè)試斷路器功能僧诚。
*
* @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);
}
/**
* 當(dāng) springms-provider-user 服務(wù)宕機(jī)或者不可用時(shí),即請(qǐng)求超時(shí)后會(huì)調(diào)用此方法蝗碎。
*
* @param id
* @return
*/
public User findByIdFallback(Long id) {
User user = new User();
user.setId(0L);
return user;
}
}
2.5 添加電影微服務(wù)啟動(dòng)類(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 微服務(wù)集成 Hystrix 斷路器實(shí)現(xiàn)失敗快速響應(yīng)湖笨,達(dá)到熔斷效果。
*
* 注解 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("【【【【【【 電影微服務(wù)-Hystrix 】】】】】】已啟動(dòng).");
}
}
三慈省、測(cè)試
/****************************************************************************************
一、電影 Ribbon 微服務(wù)集成 Hystrix 斷路器實(shí)現(xiàn)失敗快速響應(yīng)眠菇,達(dá)到熔斷效果:
1边败、注解:EnableCircuitBreaker、HystrixCommand 的編寫捎废;
2笑窜、啟動(dòng) springms-provider-user 模塊服務(wù),啟動(dòng)1個(gè)端口登疗;
3排截、啟動(dòng) springms-consumer-movie-ribbon-with-hystrix 模塊服務(wù);
4辐益、在瀏覽器輸入地址http://localhost:8070/movie/1断傲,然后頁(yè)面的信息是否有打印出來用戶的Id=0的情況,正常情況下是沒有用戶Id=0的情況信息打印的智政;
5认罩、殺死 springms-provider-user 模塊服務(wù),停止提供服務(wù)续捂;
6垦垂、在瀏覽器輸入地址http://localhost:8070/movie/1宦搬,然后頁(yè)面的信息是否有打印出來用戶的Id=0的情況,等了1秒中后有用戶Id=0的情況信息打印出來乔外;
7床三、等一會(huì)兒在啟動(dòng) springms-provider-user 模塊服務(wù)一罩,啟動(dòng)1個(gè)端口杨幼;
8、在瀏覽器輸入地址http://localhost:8070/movie/1聂渊,然后頁(yè)面的信息又有Id!=0的用戶信息打印出來差购;
總結(jié):當(dāng)遠(yuǎn)端微服務(wù)宕機(jī)或者不可用時(shí),Hystrix已經(jīng)達(dá)到快速響應(yīng)快速失敗汉嗽,起到了熔斷機(jī)制的效果欲逃。
****************************************************************************************/
四、下載地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群: 235322432
SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接
歡迎關(guān)注饼暑,您的肯定是對(duì)我最大的支持!!!