我在Spring Boot中使用hystrix javanica崩溃器,但我发现它不起作用,我的代码如下:
服务等级:
public class TestService {
@HystrixCollapser(batchMethod = "getStrList")
public Future<String> getStr(String id) {
System.out.println("single");
return null;
}
@HystrixCommand
public List<String> getStrList(List<String> ids) {
System.out.println("batch,size=" + ids.size());
List<String> strList = Lists.newArrayList();
ids.forEach(id -> strList.add("test"));
return strList;
}
}
我使用的地方:
public static void main(String[] args) {
TestService testService = new TestService();
HystrixRequestContext context = HystrixRequestContext.initializeContext();
Future<String> f1= testService.getStr("111");
Future<String> f2= testService.getStr("222");
try {
Thread.sleep(3000);
System.out.println(f1.get()); // nothing printed
System.out.println(f2.get()); // nothing printed
} catch (Exception e) {
}
context.shutdown();
}
它打印了 3 个单个
,而不是 1 batch
。
我想知道我的代码出了什么问题,最好有一个有效的示例。
最佳答案
我在网上找不到hystrix javanica示例,所以我必须阅读源代码来解决这个问题,现在已经解决了,这是我的总结:
当你在 spring-boot 中使用 hystrix(javanica) 折叠器时,你必须:
- 定义了
hystrixAspect
spring bean 并导入hystrix-strategy.xml
; - 使用
@Hystrix Collapser注释单个方法
使用@HystrixCommand
注释批量方法; - 使您的单个方法需要 1 个参数(ArgType)返回 Future ,批处理方法需要 List 返回 List 并确保参数的大小等于返回的大小。
- 设置hystrix属性
batchMethod、scope
,如果要折叠多个用户线程的请求,必须将scope设置为GLOBAL; - 在提交单个请求之前,您必须使用
HystrixRequestContext.initializeContext()
初始化 hystrix 上下文,并在请求完成时关闭
上下文;
关于java - hystrix javanica崩溃器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51145703/