Browse Source

提交

mine
袁强 5 months ago
parent
commit
a9a5c80c72
  1. 10
      yq-admin/src/main/java/yq/web/controller/nologin/NoLogin.java
  2. 6
      yq-common/pom.xml
  3. 136
      yq-common/src/main/java/yq/common/webSocket/MyWebSocketHandler.java
  4. 5
      yq-common/src/main/java/yq/common/webSocket/MyWebSocketInterceptor.java
  5. 2
      yq-common/src/main/java/yq/common/webSocket/SpringWebSocketConfig.java
  6. 6
      yq-framework/pom.xml
  7. 48
      yq-framework/src/main/java/yq/framework/web/webSocket/MyWebSocketHandler.java

10
yq-admin/src/main/java/yq/web/controller/nologin/NoLogin.java

@ -17,6 +17,7 @@ import yq.common.core.domain.entity.SysDevice;
import yq.common.core.domain.entity.SysTicket; import yq.common.core.domain.entity.SysTicket;
import yq.common.core.domain.vo.SysDeviceVo; import yq.common.core.domain.vo.SysDeviceVo;
import yq.common.core.redis.RedisCache;
import yq.common.enums.BusinessType; import yq.common.enums.BusinessType;
import yq.common.exception.ServiceException; import yq.common.exception.ServiceException;
import yq.common.utils.DateUtils; import yq.common.utils.DateUtils;
@ -57,6 +58,8 @@ public class NoLogin {
private ISysTicketService ticketService; private ISysTicketService ticketService;
@Autowired @Autowired
private IMineWarningService mineWarningService; private IMineWarningService mineWarningService;
@Autowired
private RedisCache redisCache;
@Autowired @Autowired
@ -92,7 +95,12 @@ public class NoLogin {
return AjaxResult.success(mineWarningService.insertMineWarning(mineWarning)); return AjaxResult.success(mineWarningService.insertMineWarning(mineWarning));
} }
//获取
@GetMapping("/temp")
public Map<String, Object>tempMap(String id)
{
return redisCache.getCacheMap(id);
}
//通过萤石云进行取流 //通过萤石云进行取流
@GetMapping("/list") @GetMapping("/list")
public List<Map<String, Object>>list(Integer deviceState, Long depeId) public List<Map<String, Object>>list(Integer deviceState, Long depeId)

6
yq-common/pom.xml

@ -28,7 +28,11 @@
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId> <artifactId>spring-web</artifactId>
</dependency> </dependency>
<!-- SpringBoot Websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- spring security 安全认证 --> <!-- spring security 安全认证 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>

136
yq-common/src/main/java/yq/common/webSocket/MyWebSocketHandler.java

@ -0,0 +1,136 @@
package yq.common.webSocket;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import yq.common.core.redis.RedisCache;
import yq.common.utils.spring.SpringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* @auther yq
* @data 2025/1/13
*/
@Component
public class MyWebSocketHandler implements WebSocketHandler {
private RedisCache redisCache=(RedisCache)SpringUtils.getBean(RedisCache.class);
// 存储所有连接的会话
private Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();
// 记录每个会话的重连次数
private Map<String, Integer> reconnectAttempts = new ConcurrentHashMap<>();
private static final int MAX_RECONNECT_ATTEMPTS = 5;
// WebSocket连接建立后回调的方法
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("客户端(" + session.getAttributes().get("id") + ")上线连接");
// 当连接建立时,将会话添加到会话映射中
sessionMap.put(session.getId(), session);
reconnectAttempts.put(session.getId(), 0); // 初始化重连次数
System.out.println("新的连接:" + session.getId());
System.out.println("当前在线人数:" + sessionMap.size());
}
// 接收客户端发送的消息
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
// 连接发送的消息
String msg = message.getPayload().toString();
String id = Convert.toStr(session.getAttributes().get("id"));
System.out.println("客户端(" + id + ")消息:" + msg);
// // 通过session向连接发送消息
// session.sendMessage(new TextMessage("我收到了你的消息,感谢你的来信"));
if(id.contains("dk")){
Map object = JSON.toJavaObject(msg, Map.class);
if(redisCache.hasKey(id)){
Double temp = Convert.toDouble(object.get("temp"));
Map<String, Object> cacheMap = redisCache.getCacheMap(id);
Double temp1 = Convert.toDouble(cacheMap.get("temp"));
if(temp>temp1){
redisCache.setCacheMap(id,object);
}
}else {
redisCache.setCacheMap(id,object);
}
}
}
// 向特定客户端发送消息
public void sendMessageToClient(String sessionId, String message) throws Exception {
WebSocketSession session = sessionMap.get(sessionId);
if (session != null && session.isOpen()) {
session.sendMessage(new TextMessage(message));
System.out.println("已发送消息到客户端 " + sessionId);
} else {
System.out.println("客户端连接不存在或已关闭");
}
}
// 连接出错时,回调的方法
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.out.println("收到的错误信息:" + exception);
// 处理重连逻辑
String sessionId = session.getId();
int attempts = reconnectAttempts.getOrDefault(sessionId, 0);
if (attempts < MAX_RECONNECT_ATTEMPTS) {
// 重连次数加1
reconnectAttempts.put(sessionId, attempts + 1);
System.out.println("尝试重连客户端:" + sessionId + ",已尝试 " + (attempts + 1) + " 次");
// 可以在这里调用某些方法来尝试重新建立 WebSocket 连接
// 如需要,使用 ScheduledExecutorService 等工具来定时重连
TimeUnit.SECONDS.sleep(2); // 假设每次重连等待2秒
// 重连逻辑可以实现,但这里依赖外部的 WebSocket 客户端来支持重连
} else {
System.out.println("客户端:" + sessionId + " 达到最大重连次数,停止重连");
reconnectAttempts.remove(sessionId);
}
}
// 连接关闭时,回调的方法
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("客户端(" + session.getAttributes().get("id") + ")断开连接");
// 在连接关闭时移除session并统计
sessionMap.remove(session.getId());
reconnectAttempts.remove(session.getId());
System.out.println("当前在线人数:" + getOnlineCount());
// 尝试重连
// 可以加入重连的业务逻辑
// 不过这里的实现假设是客户端主动处理断开和重连
}
// 获取当前在线人数
public int getOnlineCount() {
return sessionMap.size();
}
// WebSocketHandler 是否处理部分消息 默认返回false即可
@Override
public boolean supportsPartialMessages() {
return false;
}
public RedisCache getRedisCache() {
return redisCache;
}
}

5
yq-framework/src/main/java/yq/framework/web/webSocket/MyWebSocketInterceptor.java → yq-common/src/main/java/yq/common/webSocket/MyWebSocketInterceptor.java

@ -1,4 +1,4 @@
package yq.framework.web.webSocket; package yq.common.webSocket;
import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServerHttpResponse;
@ -15,7 +15,6 @@ public class MyWebSocketInterceptor implements HandshakeInterceptor {
@Override @Override
public boolean beforeHandshake(ServerHttpRequest servletRequest, ServerHttpResponse servletResponse, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { public boolean beforeHandshake(ServerHttpRequest servletRequest, ServerHttpResponse servletResponse, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
System.out.println("websocket前置拦截"); System.out.println("websocket前置拦截");
// //如果用到Sec-WebSocket-Protocol,可以采用getHeaders().get(key)的方法获取 // //如果用到Sec-WebSocket-Protocol,可以采用getHeaders().get(key)的方法获取
// if (servletRequest.getHeaders().get("Sec-WebSocket-Protocol") == null) { // if (servletRequest.getHeaders().get("Sec-WebSocket-Protocol") == null) {
// System.out.println("无Sec-WebSocket-Protocol,进行拦截!"); // System.out.println("无Sec-WebSocket-Protocol,进行拦截!");
@ -34,6 +33,6 @@ public class MyWebSocketInterceptor implements HandshakeInterceptor {
@Override @Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
System.out.println("websocket后置拦截"); System.out.println("websocketh后置");
} }
} }

2
yq-framework/src/main/java/yq/framework/web/webSocket/SpringWebSocketConfig.java → yq-common/src/main/java/yq/common/webSocket/SpringWebSocketConfig.java

@ -1,4 +1,4 @@
package yq.framework.web.webSocket; package yq.common.webSocket;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.EnableWebSocket;

6
yq-framework/pom.xml

@ -29,11 +29,7 @@
<artifactId>spring-boot-starter-aop</artifactId> <artifactId>spring-boot-starter-aop</artifactId>
</dependency> </dependency>
<!-- SpringBoot Websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- 阿里数据库连接池 --> <!-- 阿里数据库连接池 -->

48
yq-framework/src/main/java/yq/framework/web/webSocket/MyWebSocketHandler.java

@ -1,48 +0,0 @@
package yq.framework.web.webSocket;
import org.springframework.web.socket.*;
/**
* @auther yq
* @data 2025/1/13
*/
public class MyWebSocketHandler implements WebSocketHandler {
//建立新的 socket 连接后回调的方法
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("新连接");
//从session中获取存放的参数
session.getAttributes().get("id");
}
// 接收客户端发送的 Socket
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
// 连接发送的消息
String msg = message.getPayload().toString();
System.out.println("收到的消息:" + msg+"来自客户端:"+session.getId());
// 通过session向连接发送消息
session.sendMessage(new TextMessage("我收到了你的消息,感谢你的来信"));
}
//连接出错时,回调的方法
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.out.println("收到的错误信息:" + exception);
}
//连接关闭时,回调的方法
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("断开连接");
}
// WebSocketHandler 是否处理部分消息 默认返回false即可
@Override
public boolean supportsPartialMessages() {
return false;
}
}
Loading…
Cancel
Save