| | |
| | | package org.example.websocket.server; |
| | | |
| | | import cn.hutool.core.util.NumberUtil; |
| | | import cn.hutool.json.JSONUtil; |
| | | import com.fasterxml.jackson.core.JsonProcessingException; |
| | | import com.fasterxml.jackson.core.type.TypeReference; |
| | | import com.fasterxml.jackson.databind.ObjectMapper; |
| | | import com.fasterxml.jackson.databind.module.SimpleModule; |
| | | import com.google.common.reflect.TypeToken; |
| | | import com.google.gson.Gson; |
| | | import com.google.gson.GsonBuilder; |
| | |
| | | import org.example.util.RedisUtil; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.beans.factory.annotation.Qualifier; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.scheduling.annotation.Async; |
| | | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; |
| | | import org.springframework.stereotype.Component; |
| | | import org.springframework.util.CollectionUtils; |
| | | import org.springframework.web.bind.annotation.PostMapping; |
| | | import org.springframework.web.bind.annotation.RequestBody; |
| | | |
| | | import javax.annotation.PostConstruct; |
| | | import javax.annotation.PreDestroy; |
| | | import javax.websocket.*; |
| | | import javax.websocket.server.ServerEndpoint; |
| | | import java.io.IOException; |
| | | import java.lang.reflect.Type; |
| | | import java.math.BigDecimal; |
| | | import java.nio.ByteBuffer; |
| | | import java.text.SimpleDateFormat; |
| | | import java.util.*; |
| | | import java.util.concurrent.*; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | | import java.util.concurrent.locks.Lock; |
| | | import java.util.concurrent.locks.ReentrantLock; |
| | | import java.util.stream.Collectors; |
| | | import java.util.zip.Deflater; |
| | | import java.util.zip.DeflaterOutputStream; |
| | | |
| | | /** |
| | | * @ClassDescription: websocket服务端 |
| | |
| | | private static final Map<String, WsBo> threadLocalData = new ConcurrentHashMap<>(); |
| | | |
| | | @Autowired |
| | | @Qualifier("threadPoolTaskExecutor") |
| | | @Qualifier("markthreadPoolTaskExecutor") |
| | | private ThreadPoolTaskExecutor threadPoolTaskExecutor; |
| | | |
| | | // 定义常量:任务检查的超时时间(秒) |
| | |
| | | |
| | | private boolean hasReceivedSubscription(Session session) { |
| | | WsBo wsBo = getWsBoForSession(session.getId()); |
| | | String s = RedisUtil.get("user_" + wsBo.getUserId()); |
| | | if(null == s || s.isEmpty() && !wsBo.getToken().equals(s)){ |
| | | String s = RedisUtil.get(wsBo.getUserId().toString()); |
| | | if(StringUtils.isEmpty(s) || !wsBo.getToken().equals(s)){ |
| | | closeSession(session, "用户未登录"); |
| | | Map<String,Integer> map = new HashMap<>(); |
| | | map.put("status",1); |
| | | pushMessage(session,JSONUtil.toJsonStr(map)); |
| | | return false; |
| | | } |
| | | return wsBo != null; |
| | | } |
| | | |
| | | @OnError |
| | | public void onError(Session session, @NonNull Throwable throwable) { |
| | | onClose(); |
| | | log.error("连接发生报错: {}", throwable.getMessage()); |
| | | throwable.printStackTrace(); |
| | | } |
| | |
| | | @OnClose |
| | | public void onClose() { |
| | | int count = onlineCount.decrementAndGet(); |
| | | threadLocalData.remove(session.getId()); |
| | | wsServers.remove(this); |
| | | cancelScheduledTasks(); // 取消定时任务 |
| | | log.info("服务端断开连接,当前连接的客户端数量为:{}", count); |
| | |
| | | try { |
| | | if(!message.equals("ping")){ |
| | | WsBo bean = JSONUtil.toBean(message, WsBo.class); |
| | | if(null == bean){ |
| | | log.error("没有订阅消息"); |
| | | closeSession(session,null); |
| | | } |
| | | String s = RedisUtil.get(bean.getUserId().toString()); |
| | | if(StringUtils.isEmpty(s)){ |
| | | log.error("未登录"); |
| | | Map<String,Integer> map = new HashMap<>(); |
| | | map.put("status",1); |
| | | pushMessage(session,JSONUtil.toJsonStr(map)); |
| | | closeSession(session,null); |
| | | } |
| | | threadLocalData.put(session.getId(), bean); |
| | | } |
| | | }catch (Exception e){ |
| | |
| | | return sessionLocks.get(sessionId); |
| | | } |
| | | |
| | | // public void sendMessageToAll(String message) { |
| | | // List<CompletableFuture<Void>> futures = new ArrayList<>(); |
| | | // wsServers.forEach(ws -> { |
| | | // futures.add(CompletableFuture.runAsync(() -> { |
| | | // try { |
| | | // Session session = ws.session; |
| | | // if (session != null && session.isOpen()) { |
| | | // Lock sessionLock = getSessionLock(session.getId()); |
| | | // sessionLock.lock(); |
| | | // try { |
| | | // schedulePushMessage(session, message); |
| | | // } catch (Exception e) { |
| | | // e.printStackTrace(); |
| | | // closeSession(session, "发送消息异常,断开链接"); |
| | | // log.error("发送消息时出现异常: {}", e.getMessage()); |
| | | // } finally { |
| | | // sessionLock.unlock(); |
| | | // } |
| | | // } else { |
| | | // closeSession(session, "会话不存在或已关闭"); |
| | | // log.error("会话不存在或已关闭,无法发送消息"); |
| | | // } |
| | | // } catch (Exception e) { |
| | | // log.error("处理消息失败: {}", e.getMessage()); |
| | | // } |
| | | // }, threadPoolTaskExecutor)); |
| | | // }); |
| | | // |
| | | // // 等待所有任务执行完成 |
| | | // CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); |
| | | // } |
| | | public void sendMessageToAll(String message) { |
| | | List<CompletableFuture<Void>> futures = new ArrayList<>(); |
| | | List<Future<Void>> futures = new ArrayList<>(); |
| | | ExecutorService executorService = Executors.newFixedThreadPool(100); // 使用固定大小的线程池 |
| | | |
| | | // 收集所有活动的会话 |
| | | List<Session> activeSessions = new ArrayList<>(); |
| | | wsServers.forEach(ws -> { |
| | | futures.add(CompletableFuture.runAsync(() -> { |
| | | try { |
| | | Session session = ws.session; |
| | | if (session != null && session.isOpen()) { |
| | | Lock sessionLock = getSessionLock(session.getId()); |
| | | sessionLock.lock(); |
| | | try { |
| | | schedulePushMessage(session, message); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | closeSession(session, "发送消息异常,断开链接"); |
| | | log.error("发送消息时出现异常: {}", e.getMessage()); |
| | | } finally { |
| | | sessionLock.unlock(); |
| | | } |
| | | } else { |
| | | log.error("会话不存在或已关闭,无法发送消息"); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("处理消息失败: {}", e.getMessage()); |
| | | } |
| | | }, threadPoolTaskExecutor)); |
| | | Session session = ws.session; |
| | | if (session != null && session.isOpen()) { |
| | | activeSessions.add(session); |
| | | } else { |
| | | closeSession(session, "会话不存在或已关闭"); |
| | | log.error("会话不存在或已关闭,无法发送消息"); |
| | | } |
| | | }); |
| | | |
| | | // 等待所有任务执行完成 |
| | | CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); |
| | | // 并发处理所有活动的会话 |
| | | for (Session session : activeSessions) { |
| | | Future<Void> future = executorService.submit(() -> { |
| | | Lock sessionLock = getSessionLock(session.getId()); |
| | | try { |
| | | if (sessionLock.tryLock(100, TimeUnit.MILLISECONDS)) { |
| | | try { |
| | | schedulePushMessage(session, message); |
| | | } finally { |
| | | sessionLock.unlock(); // 确保锁只在这里释放 |
| | | } |
| | | } else { |
| | | log.error("无法获取锁,放弃对会话 {} 的操作", session.getId()); |
| | | } |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); // 重新设置中断状态 |
| | | log.error("线程被中断: {}", e.getMessage()); |
| | | } catch (JsonProcessingException e) { |
| | | log.error("JSON处理异常: {}", e.getMessage()); |
| | | } |
| | | return null; // 需要返回一个值,Void 类型的 |
| | | }); |
| | | |
| | | futures.add(future); |
| | | } |
| | | |
| | | // 等待所有任务完成或超时 |
| | | for (Future<Void> future : futures) { |
| | | try { |
| | | future.get(60, TimeUnit.SECONDS); // 指定超时时间 |
| | | } catch (TimeoutException e) { |
| | | log.error("某个任务超时,可能未能完成: {}", e.getMessage()); |
| | | // 这里可以选择是否取消该任务 |
| | | future.cancel(true); // 取消任务,设置为 true 则会中断正在执行的线程 |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); // 重新设置中断状态 |
| | | log.error("线程被中断: {}", e.getMessage()); |
| | | } catch (ExecutionException e) { |
| | | log.error("处理会话时发生异常: {}", e.getCause().getMessage()); |
| | | } |
| | | } |
| | | |
| | | // 关闭线程池 |
| | | executorService.shutdown(); |
| | | } |
| | | |
| | | |
| | | @PreDestroy |
| | | public void shutdownExecutor() { |
| | | threadPoolTaskExecutor.shutdown(); // 先关闭线程池 |
| | | try { |
| | | // 等待现有任务在指定时间内完成 |
| | | if (!threadPoolTaskExecutor.getThreadPoolExecutor().awaitTermination(60, TimeUnit.SECONDS)) { |
| | | // 如果未能完成,则强制关闭 |
| | | threadPoolTaskExecutor.getThreadPoolExecutor().shutdownNow(); |
| | | } |
| | | } catch (InterruptedException e) { |
| | | // 如果当前线程被中断,则强制关闭 |
| | | threadPoolTaskExecutor.getThreadPoolExecutor().shutdownNow(); |
| | | Thread.currentThread().interrupt(); // 还原中断状态 |
| | | } |
| | | } |
| | | |
| | | private WsBo getWsBoForSession(String sessionId) { |
| | |
| | | |
| | | private void schedulePushMessage(Session session, String message) throws JsonProcessingException { |
| | | WsBo wsBo = getWsBoForSession(session.getId()); |
| | | |
| | | if (wsBo != null) { |
| | | |
| | | String s = RedisUtil.get(wsBo.getUserId().toString()); |
| | | if(StringUtils.isEmpty(s) || !s.equals(wsBo.getToken())){ |
| | | Map<String,Integer> map = new HashMap<>(); |
| | | map.put("status",1); |
| | | pushMessage(session,JSONUtil.toJsonStr(map)); |
| | | closeSession(session,"登录状态失效"); |
| | | } |
| | | |
| | | |
| | | long currentTime = System.currentTimeMillis(); |
| | | long lastMessageTime = lastMessageTimeMap.getOrDefault(session, 0L); |
| | | int time = wsBo.getTime(); |
| | | |
| | | message = megFiltration(wsBo,message); |
| | | if (currentTime - lastMessageTime >= time * 1000) { |
| | | // 时间间隔达到要求,可以发送消息 |
| | | if(wsBo.getPushNow()){ |
| | | message = megFiltration(wsBo,message); |
| | | pushMessage(session, message); |
| | | lastMessageTimeMap.put(session, currentTime); // 更新最后发送时间 |
| | | } else { |
| | | // 时间间隔未达到,不发送消息,可以记录日志或者其他操作 |
| | | // log.info("距离上次发送消息时间未达到指定间隔,不发送消息。"); |
| | | wsBo.setPushNow(false); |
| | | }else{ |
| | | message = megFiltration(wsBo,message); |
| | | if (currentTime - lastMessageTime >= time * 1000) { |
| | | // 时间间隔达到要求,可以发送消息 |
| | | pushMessage(session, message); |
| | | lastMessageTimeMap.put(session, currentTime); // 更新最后发送时间 |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | |
| | | |
| | | private static final Gson gson = new Gson(); |
| | | private String megFiltration(WsBo wsBo,String message) throws JsonProcessingException { |
| | | List<MarketDataOut> redisValueMap = gson.fromJson(message, new TypeToken<List<MarketDataOut>>() {}.getType()); |
| | |
| | | } |
| | | if (!CollectionUtils.isEmpty(currencies)) { |
| | | Set<String> filtrationSet = currencies.stream() |
| | | .map(f -> f.getCurrency() + f.getBuy() + f.getSell()) |
| | | .map(f -> f.getCurrency() + f.getBuy() + f.getSell()) //组合过滤 ,暂时不使用,直接过滤整个币种 |
| | | // .map(f -> f.getCurrency()) |
| | | .collect(Collectors.toSet()); |
| | | // redisValueMap.removeIf(data -> filtrationSet.contains(data.getBaseAsset())); |
| | | redisValueMap.removeIf(data -> filtrationSet.contains(data.getBuyAndSell())); |
| | | } |
| | | |
| | |
| | | } |
| | | //价差 |
| | | redisValueMap = redisValueMap.stream() |
| | | .filter(data -> Double.parseDouble(data.getSpread()) >= wsBo.getSpread()) |
| | | .filter(data -> Double.parseDouble(data.getSpread()) >= wsBo.getSpread() && Double.parseDouble(data.getSpread()) <= 1000) |
| | | .collect(Collectors.toList()); |
| | | |
| | | //最低金额 |
| | | if(null != wsBo.getMinAmount()){ |
| | | redisValueMap = redisValueMap.stream() |
| | |
| | | .filter(data -> list.contains(data.getBuyAndSell())) |
| | | .forEach(data -> data.setMarker(true)); |
| | | } |
| | | map.put("uuid",wsBo.getUuid()); |
| | | map.put("current",wsBo.getCurrent()); |
| | | map.put("sizes",wsBo.getSizes()); |
| | | map.put("total",redisValueMap.size()); |
| | |
| | | } |
| | | } |
| | | |
| | | // 关闭会话的方法 |
| | | private void closeSession(Session session, String reason) { |
| | | try { |
| | | session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, reason)); |
| | | if (session != null && session.isOpen()) { |
| | | wsServers.remove(this); |
| | | log.info(reason); |
| | | session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, reason)); |
| | | } |
| | | } catch (IOException e) { |
| | | log.error("强制断开连接----异常: {}", e.getMessage()); |
| | | log.error("关闭会话时出现异常: {}", e.getMessage()); |
| | | } |
| | | wsServers.remove(this); |
| | | log.info("客户端未及时发送订阅消息,断开连接"); |
| | | } |
| | | |
| | | } |