Rx Netty:Async客户端不断获取"内容流已经处理好了#34;错误

时间:2017-06-05 22:24:22

标签: rx-java rx-netty

在下面的代码中,我尝试使用Rx Netty构建一个简单的异步HTTP客户端,向api发出75个POST请求。我遇到的问题是我一直得到一个" java.lang.IllegalStateException:内容流已经被处理掉了。"错误。

我在这里做错了什么?它与此有关:https://github.com/ReactiveX/RxNetty/issues/264

NioEventLoopGroup provider = new NioEventLoopGroup();

HttpClient<ByteBuf, ByteBuf> client = new HttpClientBuilder<ByteBuf, ByteBuf>("my-api.com", 80)
    .eventloop(provider)
    .build();

Gson gson = new Gson();

Observable.range(1, 75, Schedulers.from(provider))
    .flatMap(count -> {
      Data data = new Data("test" + count);

      return client.submit(
          HttpClientRequest.createPost("/create")
              .withHeader("Authorization", AUTH_HEADER)
              .withHeader("Content-Type", "application/json")
              .withContent(gson.toJson(data))
      );
    })
    .flatMap(response -> {
      return response.getContent().map((ByteBuf content) -> {
        return gson.fromJson(content.toString(Charset.defaultCharset()), OtherData.class);
      });
    })
    .subscribe(
        data -> logger.info("item done"),
        err -> {
          logger.error("Error", err);

          provider.shutdownGracefully();
        },
        () -> {
          logger.info("done");
          provider.shutdownGracefully();
        }
    );

1 个答案:

答案 0 :(得分:0)

我意识到当你做response.getContent()时,它需要在地图而不是flatMap中完成。例如:

NioEventLoopGroup provider = new NioEventLoopGroup();

HttpClient<ByteBuf, ByteBuf> client = new HttpClientBuilder<ByteBuf, 
ByteBuf>("my-api.com", 80)
.eventloop(provider)
.build();

Gson gson = new Gson();

Observable.range(1, 75, Schedulers.from(provider))
.flatMap(count -> {
  Data data = new Data("test" + count);

  return client.submit(
      HttpClientRequest.createPost("/create")
          .withHeader("Authorization", AUTH_HEADER)
          .withHeader("Content-Type", "application/json")
          .withContent(gson.toJson(data))
  );
})
// map not flatMap
.map(response -> {
  return response.getContent().map((ByteBuf content) -> {
    return gson.fromJson(content.toString(Charset.defaultCharset()), OtherData.class);
  });
})
.subscribe(
    data -> logger.info("item done"),
    err -> {
      logger.error("Error", err);

      provider.shutdownGracefully();
    },
    () -> {
      logger.info("done");
      provider.shutdownGracefully();
    }
);