Hystrix系列-4-Hystrix的动态配置

Hystrix默认使用Archaius来实现的动态配置,我们在上节中,使用了代码的方式来实现配置,这节,我们使用Hystrix的动态配置来实现。

1、实现一个Command,代码如下:

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即可,并覆写父类中的相应方法即可
 * @author 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方法,此处写业务逻辑
	 */
	@Override
	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);
	}
	
	/**
	 * 服务降级方法,当调用服务发生异常时,会调用该降级方法
	 */
	@Override
	protected User getFallback() {
		System.out.println("进入fallback方法!");
		User u = new User();
		u.setUsername("刘先生");
		u.setId(1l);
		
		return u;
	}
}

在application.properties配置文件中加入如下配置:

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支持的动态配置列表如下:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值