Spring Boot:新消息到达时通知用户

时间:2020-10-17 14:18:04

标签: spring-boot spring-websocket stomp

应用程序从特定用户接收新消息给其他特定用户。如果收件人是“在线”,则应通知他们有新消息。如果他们希望收到消息,则将通过http手动请求。

我尝试了许多URL组合,但是似乎无法让服务器通知用户。我在到目前为止不知道该写什么的地方都提供了到目前为止的代码。

这是我的WebSocketMessageBrokerConfigurer类:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("? ? ?");
        config.setApplicationDestinationPrefixes("? ? ?");
        config.setUserDestinationPrefix("? ? ?");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry
                .addEndpoint("/chat-notify")
                .setAllowedOrigins("*")
                .withSockJS();
    }
}

这是接收消息的控制器,将其存储在数据库中后应通知收件人:

@Autowired
private SimpMessagingTemplate webSocket;

@PostMapping
@PreAuthorize("isAuthenticated()")
public ResponseEntity<?> send(@RequestBody @Valid NewMessageDTO dto, @ApiIgnore Authentication auth) {
    User user = userService.getLoggedInUser(auth);
    Message message = messageService.messageFromNewMessageDTO(dto, user);
    messageService.save(message);

    webSocket.convertAndSendToUser("? ? ?", "? ? ?", "new message arrived");

    return new ResponseEntity<>(HttpStatus.CREATED);
}

这是带有一些javascript的简单html文件,应对此进行测试:

<html>

  <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.1/dist/sockjs.min.js"></script>
  <script src="stomp.js"></script>
  

  <script type="text/javascript">

    var socket = new SockJS('http://localhost:8080/chat-notify');
    var stompClient = Stomp.over(socket);
    stompClient.connect({ }, function(frame) {
            stompClient.subscribe("? ? ?", function(data) {
                console.log(data);
            });

    });
  </script>

</html>

0 个答案:

没有答案