天天看點

SpringCloud學習之路-Hystrix(斷路器)1.SpringCloud Hystrix簡介2.實作斷路器

1.SpringCloud Hystrix簡介

在微服務架構中,我們将系統拆分為多個微服務子產品,各個服務之間通過服務注冊與訂閱的方式互相依賴,由于每個單元都在不同的程序中運作,依賴通過遠端調用的方式執行,這樣就有可能因為網絡原因或者依賴服務自身問題出現調用故障或者延遲,這些問題也會導緻調用方的對外服務也出現延遲,若此時調用方的請求不斷增加,最後就會因為等待出現的故障的依賴方響應形成任務積壓,最終導緻自身服務的癱瘓。

為了解決這個問題,産生了斷路器等一系列的服務保護機制

SpringCloud Hystrix實作了斷路器,線程隔離等一系列的服務保護功能

2.實作斷路器

前置内容

1.啟動服務注冊中心

還不懂啟動服務注冊中心的可以看這裡https://blog.csdn.net/qq_35183385/article/details/81139489

2.啟動一個服務提供者

将項目通過Maven打包為Jar包   通過java -jar xxx.jar --server.port=8081指定端口啟動執行個體,也可以在配置檔案中設定端

這裡我們啟動端口8081

成功後,通路服務注冊中心,可以看到我們啟動的兩個執行個體已經注冊到上面了

SpringCloud學習之路-Hystrix(斷路器)1.SpringCloud Hystrix簡介2.實作斷路器

3.啟動服務消費者Ribbon,并在pom檔案裡引入Hystrix的依賴

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

在程式的啟動類ServiceRibbonApplication 加@EnableHystrix注解開啟Hystrix:

@EnableDiscoveryClient
@EnableHystrix
@EnableEurekaClient
@SpringBootApplication
public class ServiceRibbonApplication {

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

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
           

改造HelloService類,在hiService方法上加上@HystrixCommand注解。該注解對該方法建立了熔斷器的功能,并指定了fallbackMethod熔斷方法,熔斷方法直接傳回了一個字元串,字元串為”hi,”+name+”,sorry,error!”,代碼如下:

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
    }

    public String hiError(String name) {
        return "hi,"+name+",sorry,error!";
    }
}
           

完成後,我們啟動工程 通路http://localhost:8083/hello?name=xxx

可以看到顯示

hi xxx ,i am from port:8081
           

之後我們關掉8081端口的執行個體,在通路http://localhost:8083/hello?name=xxx

可以看到顯示

hi,xxx,sorry,error!
           

這就說明當 service-hi 工程不可用的時候,service-ribbon調用 service-hi的API接口時,會執行快速失敗,直接傳回一組字元串,而不是等待響應逾時,這很好的控制了容器的線程阻塞。

繼續閱讀