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

问题描述

应用程序从特定用户接收新消息给其他特定用户。如果收件人是“在线”,则应通知他们有新消息。如果他们希望收到消息,则将通过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>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)