Spring stomp - 使用 SimpMessagingTemplate 从服务器发送消息

Spring stomp - send a message from server using SimpMessagingTemplate

我正在尝试使用 stomp 从服务器向客户端发送消息。我知道在客户端使用 sock.js 和 stomp 我可以将消息从一个用户发送到另一个用户,而无需太多服务器端交互,只需在控制器方法中使用 @SendTo 注释即可。但是,我希望用户接收的消息是在服务器上生成的(实际上,我正在发送整个对象,但为了简单起见,我们只说我正在尝试发送一个字符串)。具体来说,这涉及好友请求接受,当一个用户接受好友请求时,发送请求的人应该收到一条消息,告知他的请求已被接受。因此,在简单 ajax 调用 rest 控制器方法接受请求后,该方法还应该将消息发送给其他用户。这是代码:

@RestController
@RequestMapping("/rest/user")
public class UserController{
    @Autowired
    SimpMessagingTemplate simp;

    @RequestMapping(value="/acceptFriendRequest/{id}", method=RequestMethod.GET, produces = "application/json")
    public boolean acceptFriendRequest(@PathVariable("id") int id){
        UserDTO user = getUser(); // gets logged in user
        if (user == null)
            return false;
        ... // Accept friend request, write in database, etc.
        String username = ... // gets the username from a service, works fine
        simp.convertAndSendToUser(username, "/project_sjs/notify/acceptNotification", "Some processed text!");
        return true;
    }
}

这是网络套接字配置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/sendNotification").withSockJS();

    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {

        config.enableSimpleBroker("/notify");
        config.setApplicationDestinationPrefixes("/project_sjs");
    }


}

这是 javascript 函数:

function setupWebsockets(){
    var socketClient = new SockJS("/project_sjs/sendNotification");
    stompClient = Stomp.over(socketClient);
    stompClient.connect({}, function(frame){
        stompClient.subscribe("/project_sjs/notify/acceptNotification", function(retVal){
            console.log(retVal);
        });
    });
}

当用户接受好友请求时,数据库中的一切都正常写入。当我刷新页面时,我什至可以看到其他用户现在是我的朋友。但是,其他用户从未收到他的请求已被接受的消息。 我做错了什么吗?任何帮助将不胜感激。谢谢!

我用不同的方法解决了这个问题。我没有将所有用户订阅到相同的端点“/project_sjs/notify/acceptNotification”,然后通过用户名区分他们,而是最终为每个用户订阅了不同的端点,例如“/project_sjs/notify/acceptNotification/John123”。这样,每个用户名为 John123(只有一个人,因为用户名是唯一的)的人都会收到通知。而且效果很好。