SpringCloud 進階之Hystrix(斷路器)

來源:互聯網
上載者:User

標籤:main   serve   dep   準備   分享圖片   base   cli   back   private   

1. Hystrix 斷路器
  • Hystrix是一個用於處理分布式系統的延遲和容錯的開源庫,在分布式系統裡,許多依賴不可避免的會調用失敗,
    比如逾時,異常等,Hystrix能夠保證在一個依賴出問題的情況下,不會導致整體服務失敗,避免級聯故障,以提高分
    布式系統的彈性;
  • "斷路器"本身是一種開關裝置,當某個服務單元發生故障之後,通過斷路器的故障監控(類似熔斷保險絲),向調用方
    返回一個符合預期的,可處理的備選響應(FallBack),而不是長時間的等待或者拋出調用方無法處理的異常,這樣就
    保證了服務調用方的線程不會被長時間,不必要地佔用,從而避免了故障在分布式系統中的蔓延,乃至雪崩。
1.1 服務熔斷
  • 熔斷機制是應對雪崩效應的一種微服務鏈結路保護機制;
  • 當扇出鏈路的某個微服務不可用或者回應時間太長時,會進行服務的降級,進而熔斷該節點微服務的調用,快速返回"錯誤"
    的響應資訊;當檢測到該節點微服務調用正常後恢複調用鏈路;
建立microservicecloud-provider-dept-hystrix-8001
// 參考 microservicecloud-provider-dept-8001// pom.xml<!-- hystrix --><dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-hystrix</artifactId></dependency>// application.ymleureka:  client: # 用戶端註冊進eureka服務列表內    service-url:      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka  instance:    instance-id: microservicecloud-dept8001-hystrix # 自訂hystrix相關的服務名稱資訊    prefer-ip-address: true  # 訪問路徑可以顯示IP地址// 修改DeptController@RestControllerpublic class DeptController {    @Autowired    private DeptService deptService;    @Autowired    private DiscoveryClient client;    @RequestMapping(value="/dept/get/{id}",method=RequestMethod.GET)    // 一旦調用服務方法失敗並拋出錯誤資訊後,會自動調用@HystrixCommand標註好的fallbackMethod調用類中的指定方法    @HystrixCommand(fallbackMethod="processHystrix_Get")      public Dept get(@PathVariable("id") Long id) {        Dept dept = this.deptService.get(id);        if(null == dept) {            throw new RuntimeException("該ID:"+id+"沒有對應的資訊");        }        return dept;    }    public Dept processHystrix_Get(@PathVariable("id") Long id) {        return new Dept().setDeptno(id).setDname("該ID:"+id+"沒有對應的資訊,null -- @HystrixCommand")                .setDb_source("no this database in MySQL");    }}// 修改主啟動類DeptProvider8001_Hystrix_App並添加新註解@EnableCircuitBreaker@SpringBootApplication@EnableEurekaClient // 本服務啟動後,自動註冊進eureka服務中@EnableDiscoveryClient // 服務發現@EnableCircuitBreaker // 對Hystrix熔斷機制的支援public class DeptProvider8001_Hystrix_App {    public static void main(String[] args) {        SpringApplication.run(DeptProvider8001_Hystrix_App.class, args);    }}// 測試訪問:// http://localhost:8082/consumer/dept/get/112

1.2 服務降級
  • 服務降級:整體資源快不夠了,忍痛將某些服務先關掉,待渡過難關,再開啟回來;
  • 服務降級處理是在用戶端實現完成的,與服務端沒有關係;
  • 當某個服務熔斷之後,伺服器將不再被調用,此時用戶端可以自己準備一個本地的fallback回調,返回一個預設值;
// 修改microservicecloud-api工程// 根據已有的DeptClientService介面,建立一個實現了FallbackFactory介面的類DeptClientServiceFallbackFactory@Component  // 不要忘記添加public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService> {    @Override    public DeptClientService create(Throwable arg0) {        return new DeptClientService() {            @Override            public Dept get(long id) {                return new Dept().setDeptno(id).setDname("該ID:"+id+"沒有對應的資訊,Consumer用戶端提供的降級資訊,此刻服務Provider已經關閉")                        .setDb_source("no this database in MySQL");            }            @Override            public List<Dept> list() {                return null;            }            @Override            public boolean add(Dept dept) {                return false;            }        };    }}// 修改microservicecloud-api工程, DeptClientService介面// 在註解@FeignClient中添加 fallbackFactory 屬性值@FeignClient(value="MICROSERVICECLOUD-DEPT",            fallbackFactory=DeptClientServiceFallbackFactory.class)public interface DeptClientService {    @RequestMapping(value="/dept/get/{id}", method= RequestMethod.GET)    public Dept get(@PathVariable("id") long id);    @RequestMapping(value="/dept/list", method= RequestMethod.GET)    public List<Dept> list();    @RequestMapping(value="/dept/add", method= RequestMethod.POST)    public boolean add(Dept dept);}// mvn clean// mvn install// 修改microservicecloud-consumer-dept-feign 工程// application.ymlfeign:  hystrix:    enabled: true// 測試訪問:// http://localhost:8082/consumer/dept/get/1// 然後手動關閉工程:microservicecloud-provider-dept-8001

1.3 服務監控(hystrixDashboard)建立工程microservicecloud-consumer-hystrix-dashboard
// pom.xml<!-- hystrix和hystrix-dashboard 相關 --><dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-hystrix</artifactId></dependency><dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId></dependency>// application.ymlserver:  port: 9001// 主啟動類:@SpringBootApplication@EnableHystrixDashboardpublic class DeptConsumer_DashBoard_App {    public static void main(String[] args) {        SpringApplication.run(DeptConsumer_DashBoard_App.class, args);    }}// 所有Provider微服務提供類(8001/8002/8003)都需要提供監控依賴配置// (8001/8002/8003)pom.xml<!-- actuator 監控資訊完善 --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-actuator</artifactId></dependency>// 啟動相關工程// microservicecloud-consumer-hystrix-dashboard   // 訪問: http://localhost:9001/hystrix// 3個Eureka叢集// microservicecloud-provider-dept-hystrix-8001    // 訪問: http://localhost:8001/dept/get/1    // 訪問: http://localhost:8001/hystrix.stream

參考資料:

  • SpringCloud 教程

SpringCloud 進階之Hystrix(斷路器)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.