Browse Source

Websocket更新

hanzhengyi 8 months ago
parent
commit
e9b4f9a1ee

+ 0 - 28
service-alarm/service-alarm-api/src/main/java/com/usky/alarm/RemoteUserService.java

@@ -1,28 +0,0 @@
-package com.usky.alarm;
-
-
-import com.usky.common.core.bean.ApiResult;
-import com.usky.alarm.domain.SysUserVO;
-import org.springframework.cloud.openfeign.FeignClient;
-import org.springframework.http.MediaType;
-import org.springframework.web.bind.annotation.*;
-import org.springframework.web.multipart.MultipartFile;
-
-import java.util.List;
-
-@FeignClient(contextId = "remoteUserService", value = "usky-demo")
-public interface RemoteUserService {
-
-
-
-    @GetMapping("/byUserName")
-    ApiResult<List<SysUserVO>> getByUserName(@RequestParam("userName") String userName);
-
-
-    @PostMapping("/byUserName")
-    ApiResult<List<SysUserVO>> add(@RequestBody SysUserVO sysUserVO);
-
-
-    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
-    ApiResult<String> upload(@RequestPart(value = "file") MultipartFile file);
-}

+ 14 - 0
service-alarm/service-alarm-api/src/main/java/com/usky/alarm/RemoteWebSocketService.java

@@ -0,0 +1,14 @@
+package com.usky.alarm;
+
+
+import com.usky.common.core.bean.ApiResult;
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.*;
+
+
+@FeignClient(contextId = "remoteWebSocketService", value = "service-alarm")
+public interface RemoteWebSocketService {
+
+    @PostMapping("/selfCheck")
+    ApiResult<Void> selfCheck(@RequestBody String requestBody);
+}

+ 0 - 48
service-alarm/service-alarm-api/src/main/java/com/usky/alarm/factory/RemoteUserFallbackFactory.java

@@ -1,48 +0,0 @@
-package com.usky.alarm.factory;
-
-import com.usky.common.core.bean.ApiResult;
-import com.usky.common.core.exception.BusinessException;
-import com.usky.alarm.RemoteUserService;
-import com.usky.alarm.domain.SysUserVO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.springframework.cloud.openfeign.FallbackFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.web.multipart.MultipartFile;
-
-import java.util.List;
-
-
-/**
- * 用户服务降级处理
- *
- * @author ruoyi
- */
-@Component
-public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserService>
-{
-    private static final Logger log = LoggerFactory.getLogger(RemoteUserFallbackFactory.class);
-
-    @Override
-    public RemoteUserService create(Throwable throwable)
-    {
-        log.error("用户服务调用失败:{}", throwable.getMessage());
-        return new RemoteUserService() {
-            @Override
-            public ApiResult<List<SysUserVO>> getByUserName(String userName) {
-                throw new BusinessException(throwable.getMessage());
-            }
-
-            @Override
-            public ApiResult<List<SysUserVO>> add(SysUserVO sysUserVO) {
-                throw new BusinessException(throwable.getMessage());
-            }
-
-            @Override
-            public ApiResult<String> upload(MultipartFile file) {
-                throw new BusinessException(throwable.getMessage());
-            }
-        };
-    }
-}

+ 34 - 0
service-alarm/service-alarm-api/src/main/java/com/usky/alarm/factory/RemoteWebSocketFallbackFactory.java

@@ -0,0 +1,34 @@
+package com.usky.alarm.factory;
+
+import com.usky.alarm.RemoteWebSocketService;
+import com.usky.common.core.bean.ApiResult;
+import com.usky.common.core.exception.BusinessException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.springframework.cloud.openfeign.FallbackFactory;
+import org.springframework.stereotype.Component;
+
+
+/**
+ * 用户服务降级处理
+ *
+ * @author ruoyi
+ */
+@Component
+public class RemoteWebSocketFallbackFactory implements FallbackFactory<RemoteWebSocketService>
+{
+    private static final Logger log = LoggerFactory.getLogger(RemoteWebSocketFallbackFactory.class);
+
+    @Override
+    public RemoteWebSocketService create(Throwable throwable)
+    {
+        log.error("用户服务调用失败:{}", throwable.getMessage());
+        return new RemoteWebSocketService() {
+            @Override
+            public ApiResult<Void> selfCheck(String requestBody) {
+                throw new BusinessException(throwable.getMessage());
+            }
+        };
+    }
+}

+ 12 - 0
service-alarm/service-alarm-biz/pom.xml

@@ -56,6 +56,18 @@
             <artifactId>spring-websocket</artifactId>
             <version>5.2.8.RELEASE</version>
         </dependency>
+        <dependency>
+            <groupId>com.usky</groupId>
+            <artifactId>service-alarm-api</artifactId>
+            <version>0.0.1</version>
+            <scope>compile</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.usky</groupId>
+            <artifactId>service-alarm-api</artifactId>
+            <version>0.0.1</version>
+            <scope>compile</scope>
+        </dependency>
     </dependencies>
 
     <build>

+ 0 - 60
service-alarm/service-alarm-biz/src/main/java/com/usky/alarm/controller/api/SysUserControllerApi.java

@@ -1,60 +0,0 @@
-//package com.usky.iot.controller.api;
-//
-//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-//import com.usky.common.core.bean.ApiResult;
-//import com.usky.common.core.exception.BusinessException;
-//import com.usky.common.core.util.BeanMapperUtils;
-//import com.usky.common.core.util.FileUtils;
-//import com.usky.common.core.util.GlobalUtils;
-//import com.usky.iot.domain.SysUser;
-//import com.usky.iot.service.SysUserService;
-//import com.usky.system.RemoteUserService;
-//import com.usky.system.domain.SysUserVO;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.web.bind.annotation.RestController;
-//import org.springframework.web.multipart.MultipartFile;
-//
-//import java.io.File;
-//import java.io.IOException;
-//import java.util.ArrayList;
-//import java.util.List;
-//import java.util.Optional;
-//
-//@RestController
-//public class SysUserControllerApi implements RemoteUserService {
-//
-//    @Autowired
-//    private SysUserService sysUserService;
-//    @Override
-//    public ApiResult<List<SysUserVO>> getByUserName(String userName) {
-//        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
-//        queryWrapper.eq(SysUser::getUserName,userName);
-//        return ApiResult.success(BeanMapperUtils.mapList(sysUserService.list(queryWrapper),SysUser.class,SysUserVO.class));
-//    }
-//
-//    @Override
-//    public ApiResult<List<SysUserVO>> add(SysUserVO sysUserVO) {
-//        sysUserService.save(BeanMapperUtils.map(sysUserVO, SysUser.class));
-//        return ApiResult.success(new ArrayList<>());
-//    }
-//
-//    @Override
-//    public ApiResult<String> upload(MultipartFile multipartFile) {
-//        Optional.ofNullable(multipartFile).orElseThrow(() ->  new BusinessException("文件为空"));
-//        String originalFilename = multipartFile.getOriginalFilename();
-//        String newFileName = System.currentTimeMillis() + originalFilename;
-//        File file = FileUtils.getFile(GlobalUtils.getTempBaseDir(), newFileName);
-//        String urlPath = "";
-//        try {
-//            try {
-//                multipartFile.transferTo(file);
-//            } catch (IOException e) {
-//                throw new BusinessException("文件上传失败");
-//            }
-//        } catch (Exception e) {
-//
-//        }
-//        return ApiResult.success(urlPath);
-//    }
-//}

+ 22 - 0
service-alarm/service-alarm-biz/src/main/java/com/usky/alarm/controller/api/WebSocketControllerApi.java

@@ -0,0 +1,22 @@
+package com.usky.alarm.controller.api;
+
+import com.alibaba.fastjson.JSONObject;
+import com.usky.alarm.RemoteWebSocketService;
+import com.usky.alarm.service.config.websocket.WebSocketPatrol;
+import com.usky.common.core.bean.ApiResult;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RestController;
+
+
+@RestController
+public class WebSocketControllerApi implements RemoteWebSocketService {
+
+    @Autowired
+    private WebSocketPatrol webSocketPatrol;
+    @Override
+    public ApiResult<Void> selfCheck(String requestBody) {
+        JSONObject eventVO = JSONObject.parseObject(requestBody);
+        webSocketPatrol.sendMessage(eventVO,eventVO.getString("deviceId"));
+        return ApiResult.success();
+    }
+}

+ 75 - 0
service-alarm/service-alarm-biz/src/main/java/com/usky/alarm/service/config/websocket/WebSocketPatrol.java

@@ -0,0 +1,75 @@
+package com.usky.alarm.service.config.websocket;
+
+import cn.hutool.json.JSONUtil;
+import org.springframework.stereotype.Component;
+
+import javax.websocket.OnClose;
+import javax.websocket.OnMessage;
+import javax.websocket.OnOpen;
+import javax.websocket.Session;
+import javax.websocket.server.PathParam;
+import javax.websocket.server.ServerEndpoint;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+@ServerEndpoint(value = "/webSocketPatrol/{userId}")
+@Component
+public class WebSocketPatrol {
+    private static ConcurrentHashMap<String, WebSocketPatrol> webSocketMap = new ConcurrentHashMap<>();
+    //实例一个session,这个session是websocket的session
+    private Session session;
+
+    //新增一个方法用于主动向客户端发送消息
+    public void sendMessage(Object message, String userId) {
+        Iterator<Map.Entry<String, WebSocketPatrol>> iterator = webSocketMap.entrySet().iterator();
+        while (iterator.hasNext()) {
+            Map.Entry<String, WebSocketPatrol> entry = iterator.next();
+            int index = entry.getKey().indexOf(",");
+            String result = entry.getKey().substring(0, index);
+            if (result.equals(userId)){
+                if (entry.getValue() != null) {
+                    try {
+                        entry.getValue().session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));
+                        System.out.println("【websocket消息】发送消息成功,用户=" + userId + ",消息内容" + message.toString());
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+                }
+            }
+        }
+    }
+
+    public static ConcurrentHashMap<String, WebSocketPatrol> getWebSocketMap() {
+        return webSocketMap;
+    }
+
+    public static void setWebSocketMap(ConcurrentHashMap<String, WebSocketPatrol> webSocketMap) {
+        WebSocketPatrol.webSocketMap = webSocketMap;
+    }
+
+    //前端请求时一个websocket时
+    @OnOpen
+    public void onOpen(Session session, @PathParam("userId") String userId) {
+        this.session = session;
+        webSocketMap.put(userId, this);
+        sendMessage("CONNECT_SUCCESS", userId);
+        System.out.println("【websocket消息】有新的连接,连接id" + userId);
+    }
+
+    //前端关闭时一个websocket时
+    @OnClose
+    public void onClose(@PathParam("userId") String userId) {
+        webSocketMap.remove(userId);
+        System.out.println("【websocket消息】连接断开,总数:" + webSocketMap.size());
+    }
+
+    //前端向后端发送消息
+    @OnMessage
+    public void onMessage(String message) {
+        if (!message.equals("ping")) {
+            System.out.println("【websocket消息】收到客户端发来的消息:" + message);
+        }
+    }
+}