hystrix 簡單使用, 以及動態配置更新

hystrix 簡單使用, 以及動態配置更新

概述

只介紹同步模式下簡單的使用, 有助於快速接入, 會有一些官方文檔中沒有涉及的細節.java

默認方式

HelloWorld!

public class CommandHelloWorld extends HystrixCommand<String> {

    private final String name;

    // 構造方法中傳入須要用到的數據, run 方法處理邏輯.
    public CommandHelloWorld(String name) {
        // 構造 Setter 比較麻煩, 後面會進一步介紹
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.name = name;
    }

    @Override
    protected String run() {
        // a real example would do work like a network call here
        return "Hello " + name + "!";
    }
    
    // fallback 方法可選, 若是沒有, 默認拋異常.
    @Override
    protected String getFallback() {
        return "fallback";
    }
}

構造Setter

Hystrix 講求的大而全, 設計的比較模式, 用起來不是很方便. 下面是一個構造 Setter 的實例:git

Setter setter = Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(site)) // groupKey 對command進行分組, 用於 reporting, alerting, dashboards, or team/library ownership, 也是 ThreadPool 的默認 key
        .andCommandKey(HystrixCommandKey.Factory.asKey(site)) // 能夠根據 commandKey 具體的運行時參數
        .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(site))  // 指定 ThreadPool key, 這樣就不會默認使用 GroupKey
        .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() // 初始化 Command 相關屬性
                .withMetricsRollingStatisticalWindowInMilliseconds(
                        100 * 1000) // 設置統計窗口爲100秒
                .withCircuitBreakerSleepWindowInMilliseconds(
                        10 * 1000) // 設置熔斷之後, 試探間隔爲10秒
                .withCircuitBreakerRequestVolumeThreshold(
                        10) // 設置判斷熔斷請求閾值爲10
                .withCircuitBreakerErrorThresholdPercentage(
                        80) // 設置判斷熔斷失敗率爲80%
                .withExecutionTimeoutInMilliseconds(3 * 1000)) // 設置每一個請求超時時間爲3秒
        .andThreadPoolPropertiesDefaults( // 設置和threadPool相關
                HystrixThreadPoolProperties.Setter().withCoreSize(20)); // 設置 threadPool 大小爲20(最大20個併發)

另外 threadPool 還有個設置統計窗口的選項, 由於 Hystrix 統計維度會從主線程和線程池兩個維度來統計.github

還有好多配置信息能夠配置, 這裏只提供了幾個重要的. 其餘配置參考:hystrix-configurationweb

Spring cloud 註解方式

須要用到兩個註解: @EnableCircuitBreaker, @HystrixCommand(fallbackMethod = "reliable")spring

啓動類:併發

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.web.client.RestTemplate;

@EnableCircuitBreaker
@RestController
@SpringBootApplication
public class ReadingApplication {

  @Autowired
  private BookService bookService;

  @Bean
  public RestTemplate rest(RestTemplateBuilder builder) {
    return builder.build();
  }

  @RequestMapping("/to-read")
  public String toRead() {
    return bookService.readingList();
  }

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

服務類:app

package hello;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@Service
public class BookService {

  private final RestTemplate restTemplate;

  public BookService(RestTemplate rest) {
    this.restTemplate = rest;
  }

  @HystrixCommand(fallbackMethod = "reliable")
  public String readingList() {
    URI uri = URI.create("http://localhost:8090/recommended");

    return this.restTemplate.getForObject(uri, String.class);
  }

  public String reliable() {
    return "Cloud Native Java (O'Reilly)";
  }

}

動態更新配置

Hystrix 使用 Archaius 來實現動態配置. 使用 Spring 配置方式:ide

  1. 建立配置獲取源
  2. 配置並初始化自動配置

建立配置獲取源

實現接口 PolledConfigurationSource, 並返回一個 Map. 注意 Key 爲 hystrix 配置key, 能夠參考: Hystrix-configurationui

public class DegradeConfigSource implements PolledConfigurationSource {
    @Override
    public PollResult poll(boolean initial, Object checkPoint) throws Exception {
        Map<String, Object> complete = Collections.emptyMap();
        // ...  init complete map
        // complete.put("hystrix.command.<CommandKey>.fallback.enabled"), true); 注意修改對應的 CommandKey
        return PollResult.createFull(complete);
    }
}

配置並初始化自動配置

建立一個 DynamicConfiguration, 並註冊一下就能夠了. 注意, 咱們使用了 FixedDelayPollingScheduler 來按期加載新的配置. 默認60秒加載一次.this

@Configuration
public class DegradeDynamicConfig {

    @Bean
    public DynamicConfiguration dynamicConfiguration(@Autowired DegradeConfigSource degradeConfigSource) {
        AbstractPollingScheduler scheduler = new FixedDelayPollingScheduler(30 * 1000, 60 * 1000, false);
        DynamicConfiguration configuration = new DynamicConfiguration(degradeConfigSource, scheduler);
        ConfigurationManager.install(configuration); // must install to enable configuration
        return configuration;
    }

}

參考

Hystrix-how-to-use
Hystrix-configuration
Hystrix-change-config-dynamically
hystrix-archaius-to-dynamic-config
Spring-circuit-breaker

相關文章
相關標籤/搜索