问题描述
我遇到的问题是客户端没有收到发送到用户目标的 stomp 消息。让我解释一下:
在 WebSocketMessagebrokerConfigurer 中:
public void configureMessagebroker(MessagebrokerRegistry config) {
config.enableSimplebroker("/secured/topic","/secured/user/queue");
config.setUserDestinationPrefix("/secured/user");
..
stompClient.subscribe('/secured/user/queue/notifications',function (output) {
console.log(output);
});
在日志中:
Processing SUBSCRIBE /secured/user/queue/notifications id=sub-0 session=d74f49b3-bb63-580f-b862-81647cc712b3
和发送消息的java代码:
simpMessagingTemplate.convertAndSendToUser(
"admin","/secured/user/queue/notifications",out);
导致日志:
Processing MESSAGE destination=/secured/user/queue/notifications-userd74f49b3-bb63-580f-b862-81647cc712b3 session=null payload={"from":"server","text":"hello","recipient":"admin","time":"13:29:10"}
-
但是控制台日志中没有打印任何消息。
如您所见,订阅和发送步骤中的 sessionid 是相同的。但我不明白为什么客户没有收到消息。请注意,没有用户目的地的消息工作正常。
谁能帮我一把?
解决方法
也许您应该创建自己的用户主体模型类,以确定它具有像这样的正确用户名。
str.split
您还应该创建一个 public class StompPrincipal implements Principal {
String name;
String userid;
public StompPrincipal(String name) {
this.name = name;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
@Override
public String getName() {
return name;
}
}
实现以使用您选择的名称创建用户。
DefaultHandshakeHandler
最后将这个 public class CustomHandshakeHandler extends DefaultHandshakeHandler {
// Custom class for storing principal
@Override
protected Principal determineUser(ServerHttpRequest request,WebSocketHandler wsHandler,Map<String,Object> attributes) {
// Generate principal with UUID as name
return new StompPrincipal(UUID.randomUUID().toString());
}
}
类添加到 CustomHandshakeHandler
方法中,如下所示
setHandshakeHandler
,
我尝试了很多变体,让它工作,我只是不确定它为什么工作,但我没有抱怨。我做了什么:
在 configureMessageBroker (WebSocketMessageBrokerConfigurer) 中(这真的让我很困惑,我读过的所有样本):
config.enableSimpleBroker("/secured/topic","/secured/queue","/secured/user");
convertAndSendToUser(“/secured/user”+ 用户名由 convertAndSendToUser 添加):
simpMessagingTemplate.convertAndSendToUser( "admin","/queue/notifications",out);
和我在客户端上的订阅(在这里添加用户名不太高兴..):
stompClient.subscribe("/secured/user/"+userName+"/queue/notifications",function (output) {
但它有效;-)
[编辑] 跟踪日志记录使您更容易了解正在发生的事情:
<Logger name="org.springframework.messaging" level="trace" additivity="false">
<AppenderRef ref="Console"/>
</Logger>