How to load application properties dynamically in @HystrixProperty annotation

℡╲_俬逩灬. 提交于 2019-12-11 17:13:29

问题


Working method with hardcoded values for @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);
}

I don't want to hardcode these values in @HystrixProperty annotation, instead want to read these properties from application.properties.

some thing like this: @HystrixProperty(name=HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value="${timeout.in.millis}")


回答1:


you could use a properties placeholder. Define it in your spring configuration

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

then create the properties file myapp.propertiesand put in in your classpath, as referenced in the configuration. the content could be

CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS_VALUE=500
EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS_VALUE=1500

and so on...

then you can use that parameters in your @HistrixCommand just as you wrote

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}),
 ...


来源:https://stackoverflow.com/questions/52072554/how-to-load-application-properties-dynamically-in-hystrixproperty-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!