我正在使用javax.ws.rs.sse.SseEventSource侦听我的API发送的事件。这是我的实现:
String bearer = getBearerToken();
Client client = ClientBuilder.newClient().register((ClientRequestFilter) clientRequestContext -> {
MultivaluedMap<String, Object> headers = clientRequestContext.getHeaders();
headers.add("Authorization", "Bearer " + bearer);
});
SseEventSource.target(client.target(url)).build();
sseEventSource.register(this::onMessage, this::onError);
sseEventSource.open();
除sseEventSource.open()
会阻塞大量时间(15s-40s)外,其他所有方法都效果很好。当我打印线程状态时,我得到以下信息:
"main" #1 prio=5 os_prio=31 cpu=2616.95ms elapsed=34.80s tid=0x00007fbd38009800 nid=0x1703 waiting on condition [0x00007000046a7000]
java.lang.Thread.State: WAITING (parking)
at jdk.internal.misc.Unsafe.park(java.base@11.0.6/Native Method)
- parking to wait for <0x000000070d8cbe00> (a java.util.concurrent.CountDownLatch$Sync)
at java.util.concurrent.locks.LockSupport.park(java.base@11.0.6/LockSupport.java:194)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(java.base@11.0.6/AbstractQueuedSynchronizer.java:885)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(java.base@11.0.6/AbstractQueuedSynchronizer.java:1039)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(java.base@11.0.6/AbstractQueuedSynchronizer.java:1345)
at java.util.concurrent.CountDownLatch.await(java.base@11.0.6/CountDownLatch.java:232)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl$EventHandler.awaitConnected(SseEventSourceImpl.java:417)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl.open(SseEventSourceImpl.java:174)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl.open(SseEventSourceImpl.java:163)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl.open(SseEventSourceImpl.java:158)
我想知道线程在等待什么,是否期望在继续之前在流中发布某些内容(如果这样,是否可以进行其他配置)?无论如何,我的主要问题是如何拥有更快的SseEventSource.open()
?
更新:我发现SseEventSource.open()
正在等待首次接收消息。不幸的是,由于实际连接很快建立,我必须等待30秒钟才能返回该方法。到目前为止,我还没有找到一个好的解决方案。