Browse Source

Merge branch 'master' of http://124.70.58.209:3000/ytrd-project-management/GeoHazardMonitor

hexiao 2 years ago
parent
commit
c543b3a7c3

+ 11 - 0
hazard-admin/pom.xml

@@ -19,11 +19,22 @@
 
     <dependencies>
         <!-- webSocket web端 消息推送 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-thymeleaf</artifactId>
+        </dependency>
+
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-websocket</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <scope>provided</scope>
+        </dependency>
+
         <!-- spring-boot-devtools -->
         <dependency>
             <groupId>org.springframework.boot</groupId>

+ 3 - 8
hazard-admin/src/main/java/com/ozs/web/controller/accountmanagment/MsgAlarmController.java

@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ozs.HazardApplication;
 import com.ozs.common.core.controller.BaseController;
 import com.ozs.common.core.domain.AjaxResult;
 import com.ozs.common.utils.StringUtils;
@@ -13,18 +12,15 @@ import com.ozs.service.entity.BaseCameraManagement;
 import com.ozs.service.entity.BaseRailwayManagement;
 import com.ozs.service.entity.MsgAlarm;
 import com.ozs.service.entity.MsgAlarmFrequency;
-import com.ozs.service.entity.vo.HistoricalAlarmVo;
 import com.ozs.service.entity.vo.MsgAlarmResp;
 import com.ozs.service.entity.vo.MsgAlarmVo;
 import com.ozs.service.service.BaseCameraManagementService;
 import com.ozs.service.service.BaseRailwayManagementService;
 import com.ozs.service.service.MsgAlarmFrequencyService;
 import com.ozs.service.service.MsgAlarmService;
-import com.ozs.web.core.config.WebSocketService;
 import io.swagger.annotations.ApiOperation;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.SpringApplication;
 import org.springframework.util.ObjectUtils;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PathVariable;
@@ -35,7 +31,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
 import javax.annotation.Resource;
-import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
@@ -73,9 +68,9 @@ public class MsgAlarmController extends BaseController {
         ids.add("003");
         ids.add("004");
         ids.add("005");
-
-        WebSocketService webSocketService = new WebSocketService();
-        webSocketService.sendMsgToUsers(ids);
+//
+//        WebSocketService webSocketService = new WebSocketService();
+//        webSocketService.sendMsgToUsers(ids);
         return AjaxResult.success("推送成功");
     }
 

+ 10 - 4
hazard-admin/src/main/java/com/ozs/web/core/config/WebsocketConfig.java

@@ -1,4 +1,4 @@
-package com.ozs.web.core.config;
+package com.ozs.web.controller.websocket;
 
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
@@ -6,11 +6,17 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 
 /**
  * @Author : sunhh
- * @create 2023/3/2 10:41
+ * @create 2023/3/7 16:17
  */
-
 @Configuration
-public class WebsocketConfig {
+public class WebSocketConfigOne {
+
+    /**
+     * 这个bean会自动注册使用了@ServerEndpoint注解声明的对象
+     * 没有的话会报404
+     *
+     * @return
+     */
     @Bean
     public ServerEndpointExporter serverEndpointExporter() {
         return new ServerEndpointExporter();

+ 31 - 0
hazard-admin/src/main/java/com/ozs/web/controller/websocket/WebSocketController.java

@@ -0,0 +1,31 @@
+package com.ozs.web.controller.websocket;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Author : sunhh
+ * @create 2023/3/7 16:18
+ */
+@Controller
+@RequestMapping("/pushWebSocket")
+public class WebSocketController {
+
+    @Autowired
+    private WebSocketServer webSocketServer;
+
+    @GetMapping("/publish")
+    @ResponseBody
+    public Map publish(String userId, String message) {
+        webSocketServer.sendOneMessage(userId, message);
+        HashMap<String, Object> map = new HashMap<>();
+        map.put("code", 200);
+        return map;
+    }
+}

+ 62 - 0
hazard-admin/src/main/java/com/ozs/web/controller/websocket/WebSocketServer.java

@@ -0,0 +1,62 @@
+package com.ozs.web.controller.websocket;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+import javax.websocket.OnMessage;
+import javax.websocket.OnOpen;
+import javax.websocket.Session;
+import javax.websocket.server.PathParam;
+import javax.websocket.server.ServerEndpoint;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArraySet;
+
+/**
+ * @Author : sunhh
+ * @create 2023/3/7 16:15
+ */
+@Component
+@Slf4j
+@ServerEndpoint("/webSocket/{userId}")
+public class WebSocketServer {
+    //与某个客户端的连接会话,需要通过它来给客户端发送数据
+    private Session session;
+    private static final CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
+
+    // 用来存在线连接数
+    private static final Map<String, Session> sessionPool = new HashMap<String, Session>();
+
+    /**
+     * 连接成功调用的方法
+     */
+    @OnOpen
+    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
+        try {
+            this.session = session;
+            webSockets.add(this);
+            sessionPool.put(userId, session);
+        } catch (Exception e) {
+        }
+    }
+
+    /**
+     * 收到客户端消息后调用的方法
+     */
+    @OnMessage
+    public void onMessage(String message) {
+        log.info("websocket消息: 收到客户端消息:" + message);
+    }
+
+    public void sendOneMessage(String userId, String message) {
+        Session session = sessionPool.get(userId);
+        if (session != null && session.isOpen()) {
+            try {
+                log.info("服务端推送消息:" + message);
+                session.getAsyncRemote().sendText(message);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+}

+ 0 - 113
hazard-admin/src/main/java/com/ozs/web/core/config/Server4WebSocket.java

@@ -1,113 +0,0 @@
-package com.ozs.web.core.config;
-
-import com.alibaba.fastjson2.JSONObject;
-import org.springframework.stereotype.Component;
-
-import javax.websocket.*;
-import javax.websocket.server.PathParam;
-import javax.websocket.server.ServerEndpoint;
-import java.io.IOException;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * @Author : sunhh
- * @create 2023/3/2 14:57
- */
-@Component
-@ServerEndpoint(value = "/serverForWebSocket/{userId}")
-public class Server4WebSocket {
-    // 存储登录用户的 sid 以及 session
-    private static ConcurrentHashMap<String, Session> connections = new ConcurrentHashMap<>(32);
-    // 是WebSocket的Session
-    private Session session;
-    // 统计在线人数
-    private static AtomicInteger onlineCount = new AtomicInteger();
-
-    @OnOpen //事件 --登录的人.//当你登录之后建立连接,此方法便会执行
-    public void onopen(@PathParam("userId") String userId, Session session) {
-        this.session = session;
-        System.out.println("seesionId为" + session.getId());
-        if (connections.containsKey(userId)) {
-            connections.remove(userId);
-            connections.put(userId, session);
-        } else {
-            onlineCount.incrementAndGet();
-            connections.put(userId, session);
-            System.out.println("用户:" + userId + "-" + session.getId() + "上线了-" + session);
-            System.out.println("在线人数:" + onlineCount);
-        }
-        String content = new JSONObject(connections).toString();
-        System.out.println("在线用户信息:" + content);
-    }
-
-    @OnClose
-    public void onClose(Session session) {
-        for (String userId : connections.keySet()) {
-            if (connections.get(userId).equals(session)) {
-                System.out.println("用户:" + userId + "-关闭-" + session);
-                connections.remove(session);
-                onlineCount.decrementAndGet(); // 在线数减1
-            }
-        }
-    }
-
-    @OnMessage
-    public void onMessage(String msg, Session session) {
-        System.out.println("服务端收到客户端" + session.getId() + "的消息:" + msg);
-        // 客户端向服务端发送消息,然后再推送给其他的用户,可以在这里进行设置
-        try {
-            sendMessage(msg, session);
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    @OnError
-    public void onError(Session session, Throwable error) {
-        System.out.println("发生错误");
-        error.printStackTrace();
-    }
-
-    //推送
-    public void sendMessage(String msg, Session session) throws IOException {
-//        for (Session session1 : webSocketSet) {
-//            if (session != session1)
-//                session1.getBasicRemote().sendText(msg);
-//        }
-        System.out.println("推送:" + msg);
-        session.getBasicRemote().sendText(msg);
-    }
-
-    // 推送给指定的用户群
-    public void sendMsgToUsers(List<String> ids) {
-        ids.stream().forEach(s -> {
-            System.out.println("用户:" + s + "是否能够推送:" + connections.containsKey(s));
-            if (connections.containsKey(s)) {
-                if (connections.get(s).isOpen()) {
-                    try {
-                        System.out.println("开始推送");
-                        sendMessage("hello:" + s, connections.get(s));
-                    } catch (IOException e) {
-                        throw new RuntimeException(e);
-                    }
-                }
-            }
-        });
-    }
-
-    // 推送给全部在线用户
-    public void sendMsgToAll() {
-        connections.keySet().stream().forEach(s -> {
-            if (connections.get(s).isOpen()) {
-                try {
-                    System.out.println("开始推送");
-                    sendMessage("hello:" + s, connections.get(s));
-                } catch (IOException e) {
-                    throw new RuntimeException(e);
-                }
-            }
-        });
-    }
-}

+ 0 - 21
hazard-admin/src/main/java/com/ozs/web/core/config/WebSocketService.java

@@ -1,21 +0,0 @@
-package com.ozs.web.core.config;
-
-import java.util.List;
-
-/**
- * @Author : sunhh
- * @create 2023/3/2 15:01
- */
-public class WebSocketService {
-    // 推送给指定的在线的用户
-    public void sendMsgToUsers(List<String> ids) {
-        Server4WebSocket server4WebSocket = new Server4WebSocket();
-        server4WebSocket.sendMsgToUsers(ids);
-    }
-
-    // 推送给所有用户
-    public void sendMsgToAll() {
-        Server4WebSocket server4WebSocket = new Server4WebSocket();
-        server4WebSocket.sendMsgToAll();
-    }
-}