I have a Websocket client, it sends request to Websocket server and then wait for response. I hope it can handle multiple calls (function getAppointments), but I am not sure what is wrong and it can only process one call at a time. Any suggestion? Thanks.
@Service
public class MyService {
@Autowired
private websocketClient client;
@Autowired
private MessageHandler handler;
public List<Appointment> getAppointments(Date startDate, Date endDate) {
Long messageId = generateMessageId();
Message message = new Message(messageId, startDate, endDate);
client.sendMessage(message);
Message response = handler.getResponseMessage(messageId);
return extractAppointment(response);
}
}
// Note, MessageHandler get called when Websocket client receives a message
@Service
public class MessageHandler {
private Map<Long, Message> unprocessed = new HashMap<Long, Message>();
@Override
public void handleMessage(Message response ) {
Long messageId = response.getMessageId();
unprocessed.put(messageId, response);
Thread.currentThread.interupt();
}
public Message getResponseMessage(long messageId) {
CompletableFuture<Message> future = CompletableFuture.supplyAsync(new Supplier<Message>(){
@Override
public Message get() {
Message response = unprocessed.get(messageId);
while (response == null) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
...
}
}
unprocessed.remove(messageId);
return response;
}
});
return future.get();
}
}
CodePudding user response:
