本文轉載自https://my.oschina.net/u/1169457/blog/1787414
hystrix 簡單使用, 以及動態配置更新
概述
只介紹同步模式下簡單的使用, 有助於快速接入, 會有一些官方文檔中沒有涉及的細節.
默認方式
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 的實例:
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 統計維度會從主線程和線程池兩個維度來統計.
還有好多配置信息可以配置, 這里只提供了幾個重要的. 其他配置參考:hystrix-configuration
Spring cloud 注解方式
需要用到兩個注解: @EnableCircuitBreaker
, @HystrixCommand(fallbackMethod = "reliable")
啟動類:
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); } } 服務類: 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 配置方式:
- 創建配置獲取源
- 配置並初始化自動配置
創建配置獲取源
實現接口 PolledConfigurationSource
, 並返回一個 Map. 注意 Key 為 hystrix 配置key, 可以參考: Hystrix-configuration
package com.rh.config.hystrix; import com.netflix.config.PollResult; import com.netflix.config.PolledConfigurationSource; import org.springframework.core.env.*; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.*; /** * @Auther: wangyunfei * @Date: 2019/12/10 14:12 * @Description: */ @Component /** * @Author wangyunfei * @Description 定期讀取配置文件中的hystrix配置 * @Date 2019/12/10 14:13 * @Param * @return **/ public class DegradeConfigSource implements PolledConfigurationSource { public final String HystrixPrefix = "hystrix"; //spring的Environment private ConfigurableEnvironment environment; private PropertySourcesPropertyResolver resolver; DegradeConfigSource(ConfigurableEnvironment environment) { this.environment = environment; this.resolver = new PropertySourcesPropertyResolver(this.environment.getPropertySources()); this.resolver.setIgnoreUnresolvableNestedPlaceholders(true); } @Override public PollResult poll(boolean initial, Object checkPoint) throws Exception { //Map<String, Object> complete = getHystrixConfig(); Map<String, Object> complete = getProperties(); return PollResult.createFull(complete); } @Resource private ResourceLoader resourceLoader; /** * @Author wangyunfei * @Description 獲取配置文件中的指定hystrix前綴信息 * 缺點:1)不支持yml格式 只支持properties * 2)只能讀取某一個配置文件中的信息 如果配置是寫在不同配置文件則不支持 * @Date 2019/12/20 14:58 * @Param [] * @return java.util.HashMap<java.lang.String,java.lang.String> **/ public HashMap<String,Object> getHystrixConfig() throws Exception { HashMap<String,Object> hystrixMap = new HashMap<String,Object>(); org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:application-mod.properties"); Properties props = new Properties(); props.load(resource.getInputStream()); Enumeration keys = props.propertyNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); System.out.println(key + "=" + props.getProperty(key)); if(key.contains(HystrixPrefix)) { hystrixMap.put(key, props.getProperty(key)); } } return hystrixMap; } /** * @Author wangyunfei * @Description 獲取所有配置信息 * @Date 2019/12/20 15:06 * @Param [] * @return java.util.Map<java.lang.String,java.lang.Object> **/ public Map<String, Object> getProperties() { Map<String, Object> properties = new LinkedHashMap<>(); //spring env 里面也是多個source組合的 for (Map.Entry<String, PropertySource<?>> entry : getPropertySources().entrySet()) { PropertySource<?> source = entry.getValue(); if (source instanceof EnumerablePropertySource) { EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source; for (String name : enumerable.getPropertyNames()) { if (!properties.containsKey(name) && name.contains(HystrixPrefix)) { properties.put(name, resolver.getProperty(name)); } } } } return properties; } //PropertySource也可能是組合的,通過遞歸獲取 private Map<String, PropertySource<?>> getPropertySources() { Map<String, PropertySource<?>> map = new LinkedHashMap<String, PropertySource<?>>(); MutablePropertySources sources = null; if (environment != null) { sources = environment.getPropertySources(); } else { sources = new StandardEnvironment().getPropertySources(); } for (PropertySource<?> source : sources) { extract("", map, source); } return map; } private void extract(String root, Map<String, PropertySource<?>> map, PropertySource<?> source) { if (source instanceof CompositePropertySource) { for (PropertySource<?> nest : ((CompositePropertySource) source) .getPropertySources()) { extract(source.getName() + ":", map, nest); } } else { map.put(root + source.getName(), source); } } }
配置並初始化自動配置
創建一個 DynamicConfiguration
, 並注冊一下就可以了. 注意, 我們使用了 FixedDelayPollingScheduler
來定期加載新的配置. 默認60秒加載一次.
@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配置信息等參考如下代碼 http://techblog.ppdai.com/2018/05/08/20180508/
參考
Hystrix-how-to-use
Hystrix-configuration
Hystrix-change-config-dynamically
hystrix-archaius-to-dynamic-config
Spring-circuit-breaker