SpringBoot + WebSocket+STOMP指定推送消息

简介: 本文将简单的描述SpringBoot + WebSocket+STOMP指定推送消息场景,不包含信息安全加密等,请勿用在生产环境。

一、前提条件

本文将简单的描述SpringBoot + WebSocket+STOMP指定推送消息场景,不包含信息安全加密等,请勿用在生产环境。

1.2 环境要求

JDK:11+
Maven: 3.5+
SpringBoot: 2.6+
stompjs@7.0.0

STOMP 是面向简单(或流式)文本的消息传递协议。 STOMP 提供可互操作的有线格式,以便 STOMP 客户端可以与任何 STOMP消息代理进行通信,从而在多种语言、平台和代理之间提供简单且广泛的消息互操作性。

1.3 依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、相关工具类准备

2.1 发送消息载体

@Data
public class MessageOut{
   
   
   //这里的内容按需求来写,我随便举几个
    private String userId;
    private String name;
    private String message;
    private Integer status;
}

2.2 接收消息载体

@Data
public class MessageIn{
   
   
  //这里的内容按需求来写,我随便举几个
  private String content
}

2.3 消息处理接口

在 Spring 使用 STOMP 消息传递的方法中,STOMP 消息可以路由到@Controller类。基于这点我们写一个Controller类:

@RestController
public class MessageController {
   
   

    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/message")
    @SendTo("/topic/messageTo")
    public MessageOut message(MessageIn message) {
   
   
         MessageOut m = new MessageOut(); 
         m.setMessage("有内鬼,终止交易");
         //在这里将推送地址改成 /topic/+要发送的id,即可实现点对点
         messagingTemplate.convertAndSend("/topic/12345","收到,ol");
        return m;
    }
}

2.4 为 STOMP 消息传递配置 Spring

配置类很简单,如下:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
   
   

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
   
   
        //启用一个简单的基于内存的消息代理,将问候消息传送回前缀为/topic的目的地上的客户端
        config.enableSimpleBroker("/topic");
        //指定绑定/app到用 @MessageMapping 注释的方法的消息的前缀,该前缀将用于定义所有消息映射
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
   
   
        // 注册/pda-message-websocket连接的端点,并设置允许连接的原点
        registry.addEndpoint("/pda-message-websocket").setAllowedOrigins("*");

    }
}

到这里,后端部分编写完成~

三、前端部分

这部分就是一个验证而已,没啥技术含量,我们继续以往的前端风格,给一段代码自己体会:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
  <title>Hello WebSocket</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@stomp/stompjs@7.0.0/bundles/stomp.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">浏览器不支持Javascript!Websocket依赖于启用的Javascript,请启用Javascript并重新加载此页面!</h2></noscript>
<div id="main-content" class="container">
  <div class="row">
    <div class="col-md-6">
      <form class="form-inline">
        <div class="form-group">
          <label for="connect">WebSocket 连接:</label>
          <button id="connect" class="btn btn-default" type="submit">连接</button>
          <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">断开
          </button>
        </div>
      </form>
    </div>
    <div class="col-md-6">
      <form class="form-inline">
        <div class="form-group">
          <label for="name">你叫什么?</label>
          <input type="text" id="name" class="form-control" placeholder="输入你的名字">
        </div>
        <button id="send" class="btn btn-default" type="submit">发送</button>
      </form>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12">
      <table id="conversation" class="table table-striped">
        <thead>
        <tr>
          <th>消息</th>
        </tr>
        </thead>
        <tbody id="greeting">
        </tbody>
      </table>
    </div>
  </div>
</div>
</body>
<script>
  const url = "ws://localhost:6060/pda-message-websocket";
  const stompClient = new StompJs.Client({
    
    
    brokerURL: url,
    connectHeaders: {
    
    
      // login: 'user',
      // passcode: 'password',
    },
    debug: function (str) {
    
    
      console.log(str);
    },
    //重连间隔 ms
    reconnectDelay: 5000,
    //发送心跳 ms
    heartbeatIncoming: 4000,
    //接收心跳 ms
    heartbeatOutgoing: 4000,
    logRawCommunication: false,
  });

  //默认使用WebSockets,如果浏览器不支持,则回退到SockJS
  if (typeof WebSocket !== 'function') {
    
    
    // 对于SockJS,需要设置一个工厂来创建一个新的SockJS实例
    // 用于每次(重新)连接
    stompClient.webSocketFactory = function () {
    
    
    // 请注意,URL与WebSocket URL不同
    return new SockJS('http://localhost:6060/notify');
    };
  }

  stompClient.onConnect = (frame) => {
    
    
    setConnected(true);
    console.log('Connected: ' + frame);
    //在这里将订阅改成 /topic/+自己的id,即可收到点对点发送的消息
    stompClient.subscribe('/topic/notify', (greeting) => {
    
    
      showGreeting(JSON.parse(greeting.body));
    });
  };

  stompClient.onWebSocketError = (error) => {
    
    
    console.error('Error with websocket', error);
  };

  stompClient.onStompError = (frame) => {
    
    
    console.error('Broker reported error: ' + frame.headers['message']);
    console.error('Additional details: ' + frame.body);
  };

  function setConnected(connected) {
    
    
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
    
    
      $("#conversation").show();
    }
    else {
    
    
      $("#conversation").hide();
    }
    $("#greetings").html("");
  }

  function connect() {
    
    
    stompClient.activate();
  }

  function disconnect() {
    
    
    stompClient.deactivate();
    setConnected(false);
    console.log("Disconnected");
  }

  function sendName() {
    
    
    stompClient.publish({
    
    
      destination: "/app/notify",
      body: JSON.stringify({
    
    'name': $("#name").val()})
    });
  }

  function showGreeting(message) {
    
    
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
  }

  $(function () {
    
    
    $("form").on('submit', (e) => e.preventDefault());
    $( "#connect" ).click(() => connect());
    $( "#disconnect" ).click(() => disconnect());
    $( "#send" ).click(() => sendName());
  });
</script>
</html>

四、效果

点击前端代码HTML,可以看到一下效果:

1.png

点击连接,我们可以看到控制台上打印的连接信息和订阅信息,表明我们已经成功连接到服务器。

输入名称,点击发送可以看到:
2.png

我们再看看消息返回:
3.png

点对点返回:
4.png

目录
相关文章
|
4月前
|
网络协议 前端开发 Java
SpringBoot 整合 WebSocket
WebSocket是基于TCP协议的一种网络协议,它实现了浏览器与服务器全双工通信,支持客户端和服务端之间相互发送信息。在有WebSocket之前,如果服务端数据发生了改变,客户端想知道的话,只能采用定时轮询的方式去服务端获取,这种方式很大程度上增大了服务器端的压力,有了WebSocket之后,如果服务端数据发生改变,可以立即通知客户端,客户端就不用轮询去换取,降低了服务器的压力。目前主流的浏览器都已经支持WebSocket协议了。
|
2月前
|
前端开发 JavaScript Java
【十五】springboot整合WebSocket实现聊天室
【十五】springboot整合WebSocket实现聊天室
35 0
|
2月前
|
前端开发 Java
【十四】springboot整合WebSocket
【十四】springboot整合WebSocket
53 0
|
4月前
|
Java 应用服务中间件 Maven
springboot整合websocket后启动报错:javax.websocket.server.ServerContainer not available
springboot整合websocket后启动报错:javax.websocket.server.ServerContainer not available
364 1
|
5月前
|
Java
SpringBoot:第七篇 websocket(消息推送)
SpringBoot:第七篇 websocket(消息推送)
47 0
|
消息中间件 缓存 前端开发
Springboot 整合 WebSocket ,使用STOMP协议 ,前后端整合实战 (一)
Springboot 整合 WebSocket ,使用STOMP协议 ,前后端整合实战 (一)
1659 1
Springboot 整合 WebSocket ,使用STOMP协议 ,前后端整合实战 (一)
|
消息中间件 存储 负载均衡
Springboot 整合 WebSocket ,使用STOMP协议+Redis 解决负载场景问题(二)
Springboot 整合 WebSocket ,使用STOMP协议+Redis 解决负载场景问题(二)
1048 0
Springboot 整合 WebSocket ,使用STOMP协议+Redis 解决负载场景问题(二)
|
21天前
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源
|
29天前
|
Java API Spring
SpringBoot项目调用HTTP接口5种方式你了解多少?
SpringBoot项目调用HTTP接口5种方式你了解多少?
84 2
|
29天前
|
前端开发 JavaScript Java
6个SpringBoot 项目拿来就可以学习项目经验接私活
6个SpringBoot 项目拿来就可以学习项目经验接私活
35 0