java - hystrix javanica崩溃器不起作用

标签 java spring-boot hystrix

我在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) 折叠器时,你必须:

  1. 定义了 hystrixAspect spring bean 并导入 hystrix-strategy.xml;
  2. 使用@Hystrix Collapser注释单个方法使用@HystrixCommand注释批量方法;
  3. 使您的单个方法需要 1 个参数(ArgType)返回 Future ,批处理方法需要 List 返回 List 并确保参数的大小等于返回的大小。
  4. 设置hystrix属性batchMethod、scope,如果要折叠多个用户线程的请求,必须将scope设置为GLOBAL;
  5. 在提交单个请求之前,您必须使用 HystrixRequestContext.initializeContext() 初始化 hystrix 上下文,并在请求完成时关闭上下文;

关于java - hystrix javanica崩溃器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51145703/

相关文章:

java - 如何在 JUnit 测试中使用 ObjectMapper - Spring Boot 应用

java.lang.NoClassDefFoundError : org/springframework/boot/Banner$Mode when using Hystrix

java - 如何通过JMX暴露Hystrix的断路器状态

java - 多级继承中的多个抽象类

java - 远程调用的事务管理

java - 使用菱形运算符创建通用数组

java - 如何动态绕过 spring-hibernate 中字段的验证

java - 在 Spring-Boot 上启动 Web 应用程序时出错

javascript - IntelliJ Spring启动,热部署不运行