【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

至此斷路器已經啓作用了

四、更多文章閱讀

【SpringCloud Greenwich版本】彙總
【JAVA設計模式】彙總

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章