如何在@HystrixProperty批注中动态加载应用程序属性

时间:2018-08-29 08:09:24

标签: spring properties hystrix

具有@HystricProperty的硬编码值的工作方法:

@HystrixCommand(ignoreExceptions={HttpClientErrorException.class},
        //groupKey="ProductServiceGroup",commandKey = "test", threadPoolKey = "ProductInfoDetailsThreadPool",
        commandProperties = {
                @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value="500"),
                @HystrixProperty(name=HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value="1500"),
                @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED, value="true"),
                @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value="20"),
                @HystrixProperty(name=HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_INTERRUPT_ON_TIMEOUT, value="true"),
                @HystrixProperty(name=HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value="20")
        },
        fallbackMethod = "reliable")
public Map readingList() {
    try {
        Thread.sleep(950);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    URI uri = URI.create("http://localhost:8090/recommended");
    return this.restTemplate.getForObject(uri, Map.class);
}

我不想在@HystrixProperty批注中对这些值进行硬编码,而是想从application.properties中读取这些属性。

类似这样的东西: @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS,value =“ $ {timeout.in.millis}”)

1 个答案:

答案 0 :(得分:0)

您可以使用属性占位符。 在您的spring配置中定义

<context:property-placeholder location="classpath:myapp.properties" /> 

然后创建属性文件myapp.properties,并将其放入配置中引用的类路径中。内容可能是

CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS_VALUE=500
EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS_VALUE=1500

以此类推...

然后您可以像编写时一样在@HistrixCommand中使用该参数

HystrixCommand(ignoreExceptions={HttpClientErrorException.class},
        //groupKey="ProductServiceGroup",commandKey = "test", threadPoolKey = "ProductInfoDetailsThreadPool",
        commandProperties = {
                @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value=${CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS_VALUE}),
                @HystrixProperty(name=HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value=${EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS_VALUE}),
 ...