java – 如何等待Spring WebSocketStompClient连接
作者:互联网
我使用this guide来实现一个简单的Stomp客户端:
WebSocketClient webSocketClient = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(webSocketClient);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.afterPropertiesSet();
stompClient.setTaskScheduler(taskScheduler); // for heartbeats
stompClient.setMessageConverter(new StringMessageConverter());
StompSessionHandler sessionHandler = new MySessionHandler();
stompClient.connect("ws://server/endpoint", sessionHandler);
// WAITING HERE
当连接完成时,它应该异步向MySessionHandler报告:
public class MySessionHandler extends StompSessionHandlerAdapter
{
@Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders)
{
// WAITING FOR THIS
}
}
所以问题是:在这里等待等待线路的线路如何等待?是否有一种特定的Spring方式来做到这一点?如果没有,哪种通用Java方式最适合这里?
解决方法:
也许java.util.concurrent.CountDownLatch
可以像这样解决你的问题:
CountDownLatch latch = new CountDownLatch(1);
StompSessionHandler sessionHandler = new MySessionHandler(latch);
stompClient.connect("ws://server/endpoint", sessionHandler);
// wait here till latch will be zero
latch.await();
和你的MySessionHandler实现:
public class MySessionHandler extends StompSessionHandlerAdapter {
private final CountDownLatch latch;
public MySessionHandler(final CountDownLatch latch) {
this.latch = latch;
}
@Override
public void afterConnected(StompSession session,
StompHeaders connectedHeaders) {
try {
// do here some job
} finally {
latch.countDown();
}
}
}
标签:spring-websocket,java,multithreading,spring,concurrency 来源: https://codeday.me/bug/20190727/1554243.html