1. 程式人生 > >【SpringCloud Greenwich版本】第五章:斷路器(hystrix)

【SpringCloud Greenwich版本】第五章:斷路器(hystrix)

一、SpringCloud版本

本文介紹的Springboot版本為2.1.1.RELEASE,SpringCloud版本為Greenwich.RC1,JDK版本為1.8,整合環境為IntelliJ IDEA

二、hystrix介紹

Netflix的創造了一個呼叫的庫Hystrix實現了斷路器圖案。在微服務架構中,通常有多層服務呼叫。
在這裡插入圖片描述
較低級別的服務中的服務故障可能導致使用者級聯故障。當對特定服務的呼叫達到一定閾值時(Hystrix中的預設值為5秒內的20次故障),電路開啟,不進行通話。在錯誤和開路的情況下,開發人員可以提供後備。
在這裡插入圖片描述
開放式電路會停止級聯故障,並允許不必要的或失敗的服務時間來癒合。回退可以是另一個Hystrix保護的呼叫,靜態資料或一個正常的空值。回退可能被連結,所以第一個回退使得一些其他業務電話又回到靜態資料。

三、建立hystrix服務

  • 3.1建立

由於Springboot2.1.1 Feign 已經集成了hystrix服務,所以我們只需簡單的改造cloudcustomer工程即可。

首先,根據前文啟動cloudser和兩個cloudclient服務,cloudclient服務埠分別為8002,8003,然後再修改cloudcustomer工程中的介面方法,在@FeignClient註解中增加fallback = SchedualServiceHiHystric.class
fallback 代表返回操作

package com.jthao.cloudcustomer.service;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name = "cloudclient", fallback = SchedualServiceHiHystric.class) public interface TestService { @RequestMapping
("/test") String hello(@RequestParam String name); }

定義SchedualServiceHiHystric斷路器返回保護操作,在這裡我們簡單的設定一段返回資訊

package com.jthao.cloudcustomer.service;

import org.springframework.stereotype.Component;

@Component
public class SchedualServiceHiHystric implements TestService {
    @Override
    public String hello(String name) {
        return "sorry " + name;
    }
}
  • 3.2啟動

啟動類中保持不變,@EnableDiscoveryClient服務註冊和@EnableFeignClients服務消費

package com.jthao.cloudcustomer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class CloudcustomerApplication {

    public static void main(String[] args) {
        SpringApplication.run(CloudcustomerApplication.class, args);
    }

}

Feign預設為開啟hystrix服務,各個不同版本可能不一致,所以為了保險起見,在配置檔案中開啟hystrix服務,其中feign.hystrix.enabled=true代表hystrix服務開啟,false關閉hystrix服務

eureka.client.service-url.defaultZone: http://localhost:8001/eureka/
server.port=8004
spring.application.name=cloudcustomer
feign.hystrix.enabled=true
  • 3.3訪問

通過瀏覽器多次訪問http://localhost:8004/test?name=honghong,我們可以看到如下展示

honghong===埠:8002被呼叫了===
honghong===埠:8003被呼叫了===

這時我們關閉埠為8003的cloudclient服務,再次訪問http://localhost:8004/test?name=honghong,可以看到如下展示

honghong===埠:8002被呼叫了===
sorry honghong

至此斷路器已經啟作用了