我订阅了一个订阅者
@Service
public class UserSubscribeEventListenerService {
private SimpMessagingTemplate template;
@Autowired
private GenericService<User> userService;
@Autowired
public UserSubscribeEventListenerService(SimpMessagingTemplate template) {
this.template = template;
}
@EventListener
public void handleSubscribeEvent(SessionSubscribeEvent event) {
try {
String subscribedUser = event.getUser().getName();
System.out.println("User is " + event.getUser().getName() + " Message is " + "GREETINGS" );
Thread.sleep(3000);
System.out.println("AFTER 3 seconds...." );
template.convertAndSendToUser(subscribedUser, "/user/"+subscribedUser+ "/notify", userService.getByEmail(subscribedUser));
} catch (MessagingException e) {
System.out.println(e.getCause()
+ "\n\n"
+ e.getCause());
return;
} catch (InterruptedException e) {
System.out.println(e.getCause()
+ "\n\n"
+ e.getCause());
return;
}
}
}
但客户端是下面给出的一堆JS函数
<script type="text/javascript">
//Create stomp client over sockJS protocol
var socket = new SockJS("/ws");
///var socket = new SockJS("/ws");
var stompClient = Stomp.over(socket);
$( document ).ready(function() {
stompClient.connect({}, function(s) {
stompClient.subscribe('/user/' + s.headers['user-name'] + '/notify', function(frame){
var messages = JSON.parse(frame.body)
var i;
var count = 0;
for( i in messages) {
var message = messages[i];
count ++;
if(count <= 5){
$('#user_message_addon').append(
$('<li>').append(
$('<span></span>').html(message.notificationMessage)
),
$('</li>')
)
);
}
}
});
});
});
</script>
似乎无法正常工作,在UserSubscribeEventListenerService
事件发生时没有显示或说没有获取服务器发送的消息我在客户端获得控制台输出
但我无法收到消息/通知。
任何机构都能告诉我如何解决这个问题吗?
答案 0 :(得分:1)
您是否尝试将convertAndSendToUser
参数更改为:
template.convertAndSendToUser(subscribedUser, "/notify", userService.getByEmail(subscribedUser));
或
template.convertAndSendToUser(subscribedUser, "/user/notify", userService.getByEmail(subscribedUser));
我认为spring会根据用户名更改队列名称。
或者您可以使用convertAndSend
方法执行此操作:
template.convertAndSend("/"+subscribedUser+"/notify", userService.getByEmail(subscribedUser));
或
template.convertAndSend("/user/"+subscribedUser+"/notify", userService.getByEmail(subscribedUser));
这取决于你的websocket配置(你可以在你的问题中包含它吗?)