Java高级架构面试知识点整理:基于-Hystrix-线程池技术实现资源隔离

2021/12/27 14:40:37

本文主要是介绍Java高级架构面试知识点整理:基于-Hystrix-线程池技术实现资源隔离,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

@Override
protected ProductInfo run() {
String url = “http://localhost:8081/getProductInfo?productId=” + productId;

// 调用商品服务接口
String response = HttpClientUtils.sendGetRequest(url);
return JSONObject.parseObject(response, ProductInfo.class);
}
}

我们在缓存服务接口中,根据 productId 创建 command 并执行,获取到商品数据。

@RequestMapping("/getProductInfo")
@ResponseBody
public String getProductInfo(Long productId) {
HystrixCommand getProductInfoCommand = new GetProductInfoCommand(productId);

// 通过 command 执行,获取最新商品数据
ProductInfo productInfo = getProductInfoCommand.execute();
System.out.println(productInfo); return “success”;
}

上面执行的是 execute() 方法,其实是同步的。也可以对 command 调用 queue() 方法,它仅仅是将 command 放入线程池的一个等待队列,就立即返回,拿到一个 Future 对象,后面可以继续做其它一些事情,然后过一段时间对 Futur

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

e 调用 get() 方法获取数据。这是异步的。

二、利用 HystrixObservableCommand 批量获取数据

只要是获取商品数据,全部都绑定到同一个线程池里面去,我们通过 HystrixObservableCommand 的一个线程去执行,而在这个线程里面,批量把多个 productId 的 productInfo 拉回来。

public class GetProductInfosCommand extends HystrixObservableCommand {
private String[] productIds;
public GetProductInfosCommand(String[] productIds) {
// 还是绑定在同一个线程池
super(HystrixCommandGroupKey.Factory.asKey(“GetProductInfoGroup”));
this.productIds = productIds;
}
@Override
protected Observable construct() {
return Observable.unsafeCreate((Observable.OnSubscribe) subscriber -> {
for (String productId : productIds) {
// 批量获取商品数据
String url = “http://localhost:8081/getProductInfo?productId=” + productId;
String response = HttpClientUtils.sendGetRequest(url);
ProductInfo productInfo = JSONObject.parseObject(response, ProductInfo.class);
subscriber.onNext(productInfo);
}subscriber.onCompleted();
}).subscribeOn(Schedulers.io());
}
}

在缓存服务接口中,根据传来的 id 列表,比如是以 ,分隔的 id 串,通过上面的 HystrixObservableCommand,执行 Hystrix 的一些 API 方法,获取到所有商品数据。

public String getProductInfos(String productIds) {
String[] productIdArray = productIds.split(",");
HystrixObservableCommand getProductInfosCommand = new GetProductInfosCommand(productIdArray);
Observable observable = getProductInfosCommand.observe();
observable.subscribe(new Observer() {
@Override
public void onCompleted() {
System.out.println(“获取完了所有的商品数据”);



这篇关于Java高级架构面试知识点整理:基于-Hystrix-线程池技术实现资源隔离的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程