![](/img/trans.png)
[英]Why can I subscribe to destination but I don't receive any messages for that user with Spring WebSocket STOMP (with Spring Security and Keycloak)?
[英]Stomp client doesn't receive message on user destination?
我遇到的問題是客戶端未收到發送到用戶目的地的 stomp 消息。 讓我解釋:
在 WebSocketMessageBrokerConfigurer 中:
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/secured/topic", "/secured/user/queue");
config.setUserDestinationPrefix("/secured/user");
..
在我的 stompjs 客戶端(以“管理員”身份登錄):
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 是相同的。 但我不明白為什么客戶沒有收到消息。 請注意,沒有用戶目的地的消息工作正常。
任何人都可以向我伸出援助之手嗎?
也許您應該創建自己的用戶主體 model class 以確定它具有這樣的正確用戶名。
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
class 添加到setHandshakeHandler
方法,如下所示
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("*")
.setHandshakeHandler(new CustomHandshakeHandler());
}
我嘗試了許多變化來讓它工作,我只是不確定它為什么工作,但我不抱怨。 我做了什么:
在 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.