如何在Java SDK中关闭流事件?

时间:2019-01-27 04:28:46

标签: java

我已经使用流来监听事务,并且我想在收到偶数时关闭它:

val someScenario = scenario("A scenario name")
    .exec {
        session => session.set("someVariable", Random.alphanumeric.take(20).mkString
    }
    .exec(http("Create a resource")
        .post("/v1/resource/")
        .body(StringBody("{
            "name": ${someVariable}
        }")).asJSON)

1 个答案:

答案 0 :(得分:0)

我认为这是API中的一种“鸡蛋问题”:
您无法将(可关闭的)流对象传递给事件侦听器(创建流所需的事件侦听器,这是必需的...)。

您可以(很希望)通过引入一个自定义EventListener来实现,该事件监听器具有/获取与流的关联:

...
    /*private static*/ class MyStreamClosingListener implements EventListener<TransactionResponse>()  {
       // the hash you want to compare to:
       final String myHash;          
       // the stream of interest: ..ideally we could also set it final and pass in constructor.
       SSEStream<TransactionResponse> stream;

       MyStreamClosingListener(String hash) {
          myHash = hash;
       }

       // API method
       @Override
       void onEvent(TransactionResponse resp) {
          if (null != stream && myHash.equals(resp.getHash())) {
              stream.close();
          }
       }

    } // [end-static-class]  
...

以如下方式使用它:

// the "egg":
String myHash = "12345";
MyStreamClosingListener scl = new MyStreamClosingListener(myHash);
// the "hen":
SSEStream<TransactionResponse> stream = streamserver.transactions().stream(scl);
// wire up: hopefully this happens fast enough! (before closing "onEvent" fires "by some thread")
scl.stream = stream;
// otherwise you could write it "inline" ...