WebSocket的集成

JEECG BOOT 增加websocket 旨在服务端主动向客户端推送数据,实现系统向在线用户推送消息,可群发,可对指定用户发送

jeecg boot 集成 websocket 步骤

(1)maven依赖
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

(2)WebSocket配置类

  1. package org.jeecg.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  5. @Configuration
  6. public class WebSocketConfig {
  7. /**
  8. * 注入ServerEndpointExporter,
  9. * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
  10. */
  11. @Bean
  12. public ServerEndpointExporter serverEndpointExporter() {
  13. return new ServerEndpointExporter();
  14. }
  15. }

(3) WebSocket操作类

通过该类WebSocket可以进行群推送以及单点推送

  1. package org.jeecg.modules.message.websocket;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.concurrent.CopyOnWriteArraySet;
  5. import javax.websocket.OnClose;
  6. import javax.websocket.OnMessage;
  7. import javax.websocket.OnOpen;
  8. import javax.websocket.Session;
  9. import javax.websocket.server.PathParam;
  10. import javax.websocket.server.ServerEndpoint;
  11. import org.springframework.stereotype.Component;
  12. import lombok.extern.slf4j.Slf4j;
  13. @Component
  14. @Slf4j
  15. @ServerEndpoint("/websocket/{userId}")
  16. public class WebSocket {
  17. private Session session;
  18. private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
  19. private static Map<String,Session> sessionPool = new HashMap<String,Session>();
  20. @OnOpen
  21. public void onOpen(Session session, @PathParam(value="userId")String userId) {
  22. try {
  23. this.session = session;
  24. webSockets.add(this);
  25. sessionPool.put(userId, session);
  26. log.info("【websocket消息】有新的连接,总数为:"+webSockets.size());
  27. } catch (Exception e) {
  28. }
  29. }
  30. @OnClose
  31. public void onClose() {
  32. try {
  33. webSockets.remove(this);
  34. log.info("【websocket消息】连接断开,总数为:"+webSockets.size());
  35. } catch (Exception e) {
  36. }
  37. }
  38. @OnMessage
  39. public void onMessage(String message) {
  40. log.info("【websocket消息】收到客户端消息:"+message);
  41. }
  42. // 此为广播消息
  43. public void sendAllMessage(String message) {
  44. log.info("【websocket消息】广播消息:"+message);
  45. for(WebSocket webSocket : webSockets) {
  46. try {
  47. if(webSocket.session.isOpen()) {
  48. webSocket.session.getAsyncRemote().sendText(message);
  49. }
  50. } catch (Exception e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }
  55. // 此为单点消息
  56. public void sendOneMessage(String userId, String message) {
  57. Session session = sessionPool.get(userId);
  58. if (session != null&&session.isOpen()) {
  59. try {
  60. log.info("【websocket消息】 单点消息:"+message);
  61. session.getAsyncRemote().sendText(message);
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. }
  65. }
  66. }
  67. // 此为单点消息(多人)
  68. public void sendMoreMessage(String[] userIds, String message) {
  69. for(String userId:userIds) {
  70. Session session = sessionPool.get(userId);
  71. if (session != null&&session.isOpen()) {
  72. try {
  73. log.info("【websocket消息】 单点消息:"+message);
  74. session.getAsyncRemote().sendText(message);
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. }
  80. }
  81. }

前端中VUE使用WebSocket

  1. <script>
  2. import store from '@/store/'
  3. export default {
  4. data() {
  5. return {
  6. }
  7. },
  8. mounted() {
  9. //初始化websocket
  10. this.initWebSocket()
  11. },
  12. destroyed: function () { // 离开页面生命周期函数
  13. this.websocketclose();
  14. },
  15. methods: {
  16. initWebSocket: function () {
  17. // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
  18. var userId = store.getters.userInfo.id;
  19. var url = window._CONFIG['domianURL'].replace("https://","ws://").replace("http://","ws://")+"/websocket/"+userId;
  20. this.websock = new WebSocket(url);
  21. this.websock.onopen = this.websocketonopen;
  22. this.websock.onerror = this.websocketonerror;
  23. this.websock.onmessage = this.websocketonmessage;
  24. this.websock.onclose = this.websocketclose;
  25. },
  26. websocketonopen: function () {
  27. console.log("WebSocket连接成功");
  28. },
  29. websocketonerror: function (e) {
  30. console.log("WebSocket连接发生错误");
  31. },
  32. websocketonmessage: function (e) {
  33. var data = eval("(" + e.data + ")");
  34. //处理订阅信息
  35. if(data.cmd == "topic"){
  36. //TODO 系统通知
  37. }else if(data.cmd == "user"){
  38. //TODO 用户消息
  39. }
  40. },
  41. websocketclose: function (e) {
  42. console.log("connection closed (" + e.code + ")");
  43. }
  44. }
  45. }
  46. </script>