Hystrix默认使用来实现的动态配置,我们在上节中,使用了代码的方式来实现配置,这节,我们使用Hystrix的动态配置来实现。
1、实现一个Command,代码如下:
[java]
- package com.example.demo.hystrix.command;
- import org.apache.http.HttpEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.util.EntityUtils;
- import com.example.demo.utils.ObjectMapperInstance;
- import com.example.demo.vo.User;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.netflix.hystrix.HystrixCommand;
- import com.netflix.hystrix.HystrixCommandGroupKey;
- import com.netflix.hystrix.HystrixCommandKey;
- import lombok.Getter;
- /**
- * 只需要集成HystrixCommand即可,并覆写父类中的相应方法即可
- * Administrator
- *
- */
- public class UserHystrixCommond extends HystrixCommand<User>{
- @lombok.Setter @ Getter private String id;
- public UserHystrixCommond(String id) {
- super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("UserCommandGroup"))
- .andCommandKey(HystrixCommandKey.Factory.asKey("userCommand")));
- this.id = id;
- }
- /**
- * 覆写run方法,此处写业务逻辑
- */
- protected User run() throws Exception {
- System.out.println("command user: "+Thread.currentThread().getName()+" is running......");
- CloseableHttpClient client = HttpClients.createDefault();
- HttpGet get = new HttpGet("http://localhost:7901/user/"+id);
- CloseableHttpResponse response = client.execute(get);
- HttpEntity entity = response.getEntity();
- String body = EntityUtils.toString(entity);
- ObjectMapper mapper = ObjectMapperInstance.getInstance();
- return mapper.readValue(body, User.class);
- }
- /**
- * 服务降级方法,当调用服务发生异常时,会调用该降级方法
- */
- protected User getFallback() {
- System.out.println("进入fallback方法!");
- User u = new User();
- u.setUsername("刘先生");
- u.setId(1l);
- return u;
- }
- }
[java]
- hystrix.command.userCommand.execution.isolation.strategy=SEMAPHORE //其中userCommand是我们在代码中设置的commandKey
将隔离策略由默认改为的THREAD改为SEMAPHORE,然后跑下测试,我们发现,配置没有启作用,原因如下:
Archaius 默认支持两种方式来加载本地的配置文件:
1、默认情况下,Archaius默认会加载classpath下的config.properties文件
2、在程序启动的时候,加如下的启动参数
-Darchaius.configurationSource.additionalUrls=file:///apps/myapp/application.properties
下面,我们就来测试一下:
方式一:在src/main/resources下新建config.properties文件,并加入上面的配置
方式二:在启动程序的时候,添加如下的启动参数
再次测试就会发现,我们的动态配置生效了。
Hystrix支持的动态配置列表如下:
-
-
-
-
- http://blog.csdn.net/liuchuanhong1/article/details/73718483