hystrix实用示例

HBaseUserProfileInfoGetHystrixCommand.java
public class HBaseUserProfileInfoGetHystrixCommand extends HystrixCommand<Result[]> {

	private static final Logger logger = LoggerFactory.getLogger(HBaseUserProfileInfoGetHystrixCommand.class);

	private static byte[] tableName = Bytes.toBytes("UserProfileInfo");
	static ObjectMapper objectMapper = new ObjectMapper();

	private static Configuration conf;
	// static HConnection hConnection = null;
	private static HBasePoolManager hBasePoolManager;

	static {
		try {
			conf = HBaseConfiguration.create();
			// hConnection = HConnectionManager.createConnection(conf);
			hBasePoolManager = new HBasePoolManager(); 
		} catch (Exception ex) {
			logger.error(ExceptionUtils.getFullStackTrace(ex));
		}
	}

	List<Get> gets;

	// HBasePoolManager hBasePoolManager;
	public HBaseUserProfileInfoGetHystrixCommand(List<Get> gets) {
		super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HBaseGroup"))
				.andCommandKey(HystrixCommandKey.Factory.asKey("HBaseUserProfileInfoGetCommandKey"))
				.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("HBaseUserProfileInfoGetThreadPoolKey"))
				.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(40))
				.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
						.withExecutionIsolationThreadTimeoutInMilliseconds(10000)
						.withCircuitBreakerRequestVolumeThreshold(200)
						)
			);

		this.gets = gets;
	}



	@Override
	protected Result[] run() throws Exception {
		// TODO Auto-generated method stub
		Transaction catTran = null;
		HTableInterface table = null;
		Result[] rtn = null;
		try {
			catTran = Cat.newTransaction(DataProxyCatConstants.TYPE_HBase, DataProxyCatConstants.Name_ReadProfileHBase);
			/*
			 * if(hConnection == null || hConnection.isTableEnabled(tableName)
			 * == false) { hConnection =
			 * HConnectionManager.createConnection(conf); } table =
			 * hConnection.getTable(tableName);
			 */
			table = hBasePoolManager.getConn(tableName);
			rtn = table.get(gets);
			catTran.setStatus(com.dianping.cat.message.Message.SUCCESS);
		} catch (Exception ex) {
			logger.warn(ExceptionUtils.getFullStackTrace(ex));
			catTran.setStatus(ex);
		} finally {
			catTran.complete();
			if (table != null) {
				table.close();
			}
		}
		return rtn;
	}
}
调用HBaseUserProfileInfoGetHystrixCommand
	public Map<String, QualifierData> getList(String rowkv, List<String> tags, List<Integer> maxVersions) {
		rowkv = rowkv.toLowerCase();
		Transaction catTran = null;
		Result[] results = null;
		HBaseResult rtn = new HBaseResult();

		try {
			catTran = Cat.newTransaction(DataProxyCatConstants.TYPE_Hystrix, DataProxyCatConstants.Name_ReadProfileHBase);

			List<Get> gets = new ArrayList<>();
			for (int i = 0; i < tags.size(); i++) {
				try {
					Get get = new Get(Bytes.toBytes(rowkv));
					byte[] qualifier = Bytes.toBytes(tags.get(i));
					get.addColumn(family, qualifier);
					int maxVersion = maxVersions.get(i);
					get.setMaxVersions(maxVersion);

					gets.add(get);
				} catch (Exception e) {
					logger.error(ExceptionUtils.getFullStackTrace(e));
				}
			}

			HBaseUserProfileInfoGetHystrixCommand command = new HBaseUserProfileInfoGetHystrixCommand(gets);

			results = command.execute();

			if (results == null) {
				return null;
			}

			for (Result result : results) {
				for (KeyValue kv : result.raw()) {
					String q = Bytes.toString(kv.getQualifier());
					String v = Bytes.toString(kv.getValue());
					long t = kv.getTimestamp();

					rtn.add(rowkv, q, v, t);
				}
			}

			catTran.setStatus(com.dianping.cat.message.Message.SUCCESS);
		} catch (Exception e) {
			logger.warn(ExceptionUtils.getFullStackTrace(e));
			catTran.setStatus(e);
		} finally {
			catTran.complete();
		}

		return rtn.getQualifiers(rowkv);
	}


好的,下面是一个简单的Spring Cloud Hystrix的代码示例: 1. 添加Hystrix依赖 在aven项目中,需要在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> <version>2.2.6.RELEASE</version> </dependency> ``` 2. 创建服务接口 创建服务接口,并在接口中定义需要调用的方法。 例如: ``` public interface OrderService { String getOrder(String orderId); } ``` 3. 创建服务实现类 创建服务实现类,并在实现类中实现服务接口中的方法。 例如: ``` @Service public class OrderServiceImpl implements OrderService { @Autowired private RemoteService remoteService; @Override @HystrixCommand(fallbackMethod = "fallbackGetOrder") public String getOrder(String orderId) { return remoteService.getOrder(orderId); } private String fallbackGetOrder(String orderId) { return "Failed to get order"; } } ``` 4. 配置Hystrix 可以使用@HystrixCommand注解配置Hystrix的参数,例如: ``` @HystrixCommand( fallbackMethod = "fallbackGetOrder", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000") } ) public String getOrder(String orderId) { return remoteService.getOrder(orderId); } ``` 5. 测试Hystrix 可以通过以下方式测试Hystrix: ``` @Autowired private OrderService orderService; @RequestMapping("/order/{orderId}") public String getOrder(@PathVariable String orderId) { return orderService.getOrder(orderId); } ``` 以上是Spring Cloud Hystrix的简单使用示例,更多内容可以参考官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值