SpringCloud Hystrix

1.簡介

所謂的熔斷機(jī)制和日常生活中見到電路保險(xiǎn)絲是非常相似的,當(dāng)出現(xiàn)了問題之后,保險(xiǎn)絲會(huì)自動(dòng)燒斷,以保護(hù)我們的電器, 那么如果換到了程序之中呢?當(dāng)現(xiàn)在服務(wù)的提供方出現(xiàn)了問題之后整個(gè)的程序?qū)⒊霈F(xiàn)錯(cuò)誤的信息顯示,而這個(gè)時(shí)候如果不想出現(xiàn)這樣的錯(cuò)誤信息,而希望替換為一個(gè)錯(cuò)誤時(shí)的內(nèi)容。
本文只做簡單的介紹,之前在看簡書的時(shí)候也看到了一篇寫的非常詳細(xì)的文章,有興趣的話大家可以看看。

《服務(wù)容錯(cuò)保護(hù)-Spring Cloud Hystrix》

2.配置

Maven

引入spring-cloud-starter-netflix-hystrix

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

開啟Hystrix

添加@EnableCircuitBreaker注解來開啟Hystrix,當(dāng)然你可以直接添加@SpringCloudApplication注解,@SpringCloudApplication包含@SpringBootApplication,@EnableDiscoveryClient@EnableCircuitBreaker。

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

對(duì)方法添加Hystrix

@DefaultProperties(defaultFallback = "defaultFallback"):設(shè)定默認(rèn)降級(jí)方法
@HystrixCommand(fallbackMethod = "fallback"):設(shè)定某個(gè)方法的降級(jí)方法
其中注解中的@HystrixProperty中的參數(shù)可以在HystrixCommandProperties類中去查找,關(guān)于其屬性的含義可以參考官方文檔。
在下面示例代碼中我們配合了遠(yuǎn)程調(diào)用,實(shí)際上一切符合熔斷條件的情境我們都可以使用Hystrix。

@DefaultProperties(defaultFallback = "defaultFallback")
@RestController
public class HystrixController {
    @GetMapping("/getProductInfoList")
    @HystrixCommand(fallbackMethod = "fallback",commandProperties =
            {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
            })
    public String getProductInfoList()
    {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForObject("http://127.0.0.1:8003/product/listForOrder",
                Arrays.asList("123") ,
                String.class);
    }

    private String fallback()
    {
        return "太擁擠了,請(qǐng)稍后再試";
    }

    private String defaultFallback()
    {
        return "默認(rèn)太擁擠了,請(qǐng)稍后再試";
    }
}

這樣就可以使用Hytrix為我們帶來熔斷功能了。

3.在Feign中使用Hytrix

Maven

由于在Feign包中已經(jīng)包含了Hystrix,所以我們不用重新引用Hystrix。

配置文件

開啟Hystrix功能,此處注意是enabled!

feign:
 hystrix:
  enabled: true

配置Hystrix參數(shù)

hystrix:
  command:
      default:
        execution:
          isolation:
            thread:
              timeoutInMilliseconds: 10000

代碼配置

在FeignClient類的注解上添加fallback并指定所需要降級(jí)的類,這個(gè)類實(shí)現(xiàn)FeignClient的接口即可。在以Jar的方式引用FeignClient的時(shí)候需要在配置類上添加@ComponentScan來掃描

/**
 * @author BaoZhou
 * @date 2018/8/29
 */
@FeignClient(name = "PRODUCT",fallback = ProductClient.ProductClientFallback.class)
public interface ProductClient {

    /**
     * 獲取指定ID對(duì)應(yīng)的商品
     * @param productIdList
     * @return
     */
    @PostMapping("/product/listForOrder")
    List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIdList);


    /**
     * 減庫存
     * @param decreaseStockInputs
     */
    @PostMapping("/product/decreaseStock")
    void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputs);

    static class ProductClientFallback implements ProductClient{

        @Override
        public List<ProductInfoOutput> listForOrder(List<String> productIdList) {
            return null;
        }

        @Override
        public void decreaseStock(List<DecreaseStockInput> decreaseStockInputs) {

        }
    }
}

至此我們就配置完畢了。

4.Hystrix DashBoard

Hystrix DashBoard是一款監(jiān)控Hystrix 情況的組件

Maven

引入spring-cloud-starter-hystrix-dashboard

  <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
            <version>1.4.4.RELEASE</version>
        </dependency>

開啟Hystrix DashBoard

添加@EnableHystrixDashboard注解

@ComponentScan(basePackages = {"com.bzcoder.product.client"})
@ComponentScan(basePackages={"com.bzcoder.order.controller"})
@EnableFeignClients(basePackages =  {"com.bzcoder.product.client"})
@SpringCloudApplication
@EnableHystrixDashboard
@EnableSwagger2
public class OrderApplication {

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

訪問Hystrix DashBoard

訪問服務(wù)地址+hystrix即可訪問,例如:http://localhost:8002/hystrix,按照首頁的要求填寫參數(shù),即可進(jìn)入監(jiān)控界面

Hystrix DashBoard

這個(gè)頁面能夠可視化的查看熔斷狀態(tài),請(qǐng)求狀態(tài)。


Hystrix DashBoard詳情頁面

那么有關(guān)于SpringCloud Hystrix的簡單介紹就到這里了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容