我使用stomp客户端和Web套接字将数据从spring boot发送到客户端。它能够将数据发送给第一个用户,但是一旦用户增加,它就只为某些用户提取数据。这看起来很奇怪,因为它的行为应该对所有用户都相同。经过广泛研究后我发现原因是因为我连接到队列('/ user / queue')并且有多个客户端正在监听它。如何避免这个问题或者无法解决这个问题。 我的控制器代码 -
@Controller
public class ScheduledUpdatesOnTopic {
@Autowired
public SimpMessageSendingOperations messagingTemplate;
@Autowired
private SimpMessagingTemplate template;
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String json[][] = {{"Lokesh Gupta","34","India",df.format(date)},{"Meenal","23","Pakistan",df.format(date)},{"Gongo","12","Indonesia",df.format(date)},{"Abraham","17","US",df.format(date)},{"Saddam","56","Iraq",df.format(date)},{"Yimkov","67","Japan",df.format(date)},{"Salma","22","Pakistan",df.format(date)},{"Georgia","28","Russia",df.format(date)},{"Jaquline","31","Sri Lanka",df.format(date)},{"Chenchui","78","China",df.format(date)}};
String t[] = {"Lokesh Gupta","34","India","11/8/2017"};
String temp[][];
int p=0;
int count=0;
private MessageHeaderInitializer headerInitializer;
@MessageMapping("/hello")
public void start(SimpMessageHeaderAccessor accessor) throws Exception
{
String applicantId=accessor.getSessionId();
System.out.println("session id " + applicantId);
this.messagingTemplate.convertAndSendToUser(applicantId,"/queue/cache",json,createHeaders(applicantId));
}
private MessageHeaders createHeaders(String sessionId) {
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
if (getHeaderInitializer() != null) {
getHeaderInitializer().initHeaders(headerAccessor);
}
headerAccessor.setSessionId(sessionId);
headerAccessor.setLeaveMutable(true);
return headerAccessor.getMessageHeaders();
}
public MessageHeaderInitializer getHeaderInitializer() {
return this.headerInitializer;
}
public void setHeaderInitializer(MessageHeaderInitializer headerInitializer) {
this.headerInitializer = headerInitializer;
}
客户端html是 -
var socket = new SockJS('/gs-guide-websocket');
var stompClient = Stomp.over(socket);
stompClient.connect({ }, function(frame) {
console.log('Connected this ' + frame);
stompClient.subscribe("/user/queue/cache", function(data) {
// code to display this data..........
});
我必须使用队列,因为这是将数据发送到特定会话ID的唯一方法。任何帮助将不胜感激!!
答案 0 :(得分:0)
听起来您需要使用“请求 - 回复”消息模式。
当客户端连接到公共队列上的服务器时,它包含一个私有返回地址。此返回地址可用于生成专用于服务器和客户端的新私有消息队列名称(因为它们是唯一知道私有返回地址的2个。服务器然后可以通过私有消息队列发送客户端数据。
例如,返回地址可以是随机UUID,私有队列名称可以是/ queue / private。
此处更正式地解释了此“请求 - 回复”消息传递模式,以及其他有用的消息传递模式: http://www.enterpriseintegrationpatterns.com/patterns/messaging/ReturnAddress.html