天天看點

SpringCloud之Hystrix斷路器

Hystrix斷路器

    微服務架構中,通常多個服務之間會互相調用,一些基礎服務的故障可能會導緻級聯故障,進而導緻整個系統不可用,這就是雪崩效應。服務的雪崩效應是一種因為服務提供者的不可用導緻服務消費者的不可用,并将這種不可用逐漸放大的過程。

    Hystrix是一個用于處理分布式系統的延遲和容錯的開源庫。分布式系統中,有許多依賴會因為逾時、異常等原因導緻調用失敗。Hystrix能夠保證在一個依賴出問題的情況下,不會導緻整體服務失敗,避免級聯故障,以提高系統穩定性(類似于電路中的保險絲)。

    在Hystrix中有一個降級操作(Fallback),對于查詢操作,我們可以實作一個fallback方法,當請求方異常時,可以使用fallback方法的傳回值,而fallback方法的傳回值一般設定的預設值或者來自于緩存。

項目建構,還是在之前的consumer基礎上進行修改:

添加依賴:

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

主類添加使能注解**@EnableCircuitBreaker**

package com.zh.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient // 開啟EurekaClient功能
@EnableFeignClients
@EnableCircuitBreaker   //開啟hystrix
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}
           

application.yml添加配置:

feign:
  hystrix:
    enabled: true  #開啟熔斷政策
           

@FeignClient中添加fallbackFactory屬性

package com.zh.cloud.api;

import com.zh.cloud.fallback.UserControllerFallback;
import com.zh.cloud.model.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@FeignClient(value = "provider", fallbackFactory = UserControllerFallback.class)   //調用的服務名
public interface UserControllerInter {
    @GetMapping("/v1/user/list")   //此處的調用路徑必須與服務提供者的路徑相同
    public List<User> queryUser();
}
           

編寫UserControllerFallback類

package com.zh.cloud.fallback;

import com.zh.cloud.api.UserControllerInter;
import com.zh.cloud.model.User;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserControllerFallback implements FallbackFactory<UserControllerInter> {

    @Override
    public UserControllerInter create(Throwable throwable) {
        return new UserControllerInter() {
            @Override
            public List<User> queryUser() {
                List<User> list = new ArrayList<>();
                User user = new User();
                user.setId(999);
                user.setName("降級名稱");
                user.setAge(88);
                user.setAddress("降級位址");
                list.add(user);
                return list;
            }
        };
    }
}
           

注:若接口有多個,則隻需要對需要降級的controller中的方法進行重寫,其餘的不用動即可。

啟動之後測試,看到可以正常通路,kill掉provider之後再次通路,就可以看到熔斷的效果了。

SpringCloud之Hystrix斷路器

完整代碼位址:

https://gitee.com/superbutton/spring-cloud-study/tree/develop/springcloud-hystrix-application
           

Hystrix可視化資料監控Dashboard

    Hystrix還提供了準實時的調用監控(Hystrix Dashboard),Hystrix會持續記錄所有通過Hystrix發起的請求執行資訊。并以統計圖表和圖形的形式展示給使用者,包括每秒執行的請求數量,成功、失敗數量等。

項目建構(在hystrix基礎上搭建):

1、添加:Hystrix、Actuator、Hystrix-dashboard的依賴

<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>
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
 </dependency>
           

2、主類添加@EnableHystrixDashboard 開啟Dashboard并

注冊HystrixMetricsStreamServlet

package com.zh.cloud;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableDiscoveryClient // 開啟EurekaClient功能
@EnableFeignClients
@EnableCircuitBreaker   //開啟hystrix
@EnableHystrixDashboard
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    @Bean
    public ServletRegistrationBean registrationBean() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}
           

注:在2.x之前的版本中,會自動注入該Servlet的,但是在2.x之後的版本,沒有自動注冊該Servlet。

通路如下位址就可以檢視服務的流資料,注:ip和端口是對應服務的ip+端口

http://ip:端口/hystrix.stream

如下圖所示:

SpringCloud之Hystrix斷路器

檢視Hystrix Dashboard,注:ip和端口是對應服務的ip+端口

http://ip:端口/hystrix

如下圖所示:

SpringCloud之Hystrix斷路器

調用consumer的接口并不斷重新整理,模拟高并發的場景,觀察Hystrix Dashboard界面的變化。

SpringCloud之Hystrix斷路器

完整代碼如下:

https://gitee.com/superbutton/spring-cloud-study/tree/develop/springcloud-hystrix-dashboard
           

相關解釋如下:

SpringCloud之Hystrix斷路器

繼續閱讀