| | |
| | | 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.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.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 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){ |
| | |
| | | sessionLock.unlock(); |
| | | } |
| | | } else { |
| | | closeSession(session, "会话不存在或已关闭"); |
| | | log.error("会话不存在或已关闭,无法发送消息"); |
| | | } |
| | | } catch (Exception e) { |
| | |
| | | |
| | | 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); // 更新最后发送时间 |
| | | } |
| | | } |
| | | } |
| | | } |
| | |
| | | .collect(Collectors.toList()); |
| | | } |
| | | //价差 |
| | | if(wsBo.getSpread() > 0){ |
| | | redisValueMap = redisValueMap.stream() |
| | | .filter(data -> Double.parseDouble(data.getSpread()) >= wsBo.getSpread()) |
| | | .collect(Collectors.toList()); |
| | | } |
| | | redisValueMap = redisValueMap.stream() |
| | | .filter(data -> Double.parseDouble(data.getSpread()) >= wsBo.getSpread() && Double.parseDouble(data.getSpread()) <= 1000) |
| | | .collect(Collectors.toList()); |
| | | |
| | | //最低金额 |
| | | if(null != wsBo.getMinAmount()){ |
| | | redisValueMap = redisValueMap.stream() |
| | |
| | | .collect(Collectors.toList()); |
| | | } |
| | | //自选标记 |
| | | if(null != wsBo.getIsMarker()){ |
| | | List<String> list = Arrays.asList(wsBo.getIsMarker().split(",")); |
| | | String mark = RedisUtil.get(wsBo.getUserId() + "_mark"); |
| | | if(StringUtils.isNoneEmpty(mark)){ |
| | | List<String> list = Arrays.asList(mark.split(",")); |
| | | 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()); |
| | |
| | | Collections.sort(marketDataList, new Comparator<MarketDataOut>() { |
| | | @Override |
| | | public int compare(MarketDataOut a, MarketDataOut b) { |
| | | // 将买入总价和卖出总价转换为 BigDecimal |
| | | BigDecimal buyTotalPriceA = new BigDecimal(a.getBuyTotalPrice()); |
| | | BigDecimal buyTotalPriceB = new BigDecimal(b.getBuyTotalPrice()); |
| | | BigDecimal sellTotalPriceA = new BigDecimal(a.getSellTotalPrice()); |
| | | BigDecimal sellTotalPriceB = new BigDecimal(b.getSellTotalPrice()); |
| | | BigDecimal spreadA = new BigDecimal(a.getSpread()); |
| | | BigDecimal spreadB = new BigDecimal(b.getSpread()); |
| | | return spreadB.compareTo(spreadA); |
| | | |
| | | // 检查 a 和 b 的买入总价或卖出总价是否大于 1000 |
| | | boolean aBuyOrSellAbove1000 = buyTotalPriceA.compareTo(new BigDecimal("1000")) > 0 || sellTotalPriceA.compareTo(new BigDecimal("1000")) > 0; |
| | | boolean bBuyOrSellAbove1000 = buyTotalPriceB.compareTo(new BigDecimal("1000")) > 0 || sellTotalPriceB.compareTo(new BigDecimal("1000")) > 0; |
| | | |
| | | if (aBuyOrSellAbove1000 && !bBuyOrSellAbove1000) { |
| | | return -1; // a 应排在 b 前面 |
| | | } else if (!aBuyOrSellAbove1000 && bBuyOrSellAbove1000) { |
| | | return 1; // b 应排在 a 前面 |
| | | } else { |
| | | // a 和 b 都大于 1000 或都小于等于 1000 |
| | | // 先按照 spread 的降序排列 |
| | | int spreadComparison = spreadB.compareTo(spreadA); |
| | | if (spreadComparison != 0) { |
| | | return spreadComparison; // 先按照 spread 排序 |
| | | } else { |
| | | // 如果 spread 相同,再按照买入总价或卖出总价的升序排列 |
| | | if (aBuyOrSellAbove1000) { |
| | | // 对于买入总价或卖出总价大于 1000 的记录 |
| | | return buyTotalPriceA.compareTo(buyTotalPriceB); // 按照买入总价升序排序 |
| | | } else { |
| | | // 对于买入总价或卖出总价小于等于 1000 的记录 |
| | | return buyTotalPriceA.compareTo(buyTotalPriceB); // 可以选择卖出总价或买入总价的升序排序 |
| | | } |
| | | } |
| | | } |
| | | } |
| | | }); |
| | | } |
| | |
| | | |
| | | // 关闭会话的方法 |
| | | private void closeSession(Session session, String reason) { |
| | | try { |
| | | session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, reason)); |
| | | } catch (IOException e) { |
| | | log.error("强制断开连接----异常: {}", e.getMessage()); |
| | | } |
| | | threadLocalData.remove(session.getId()); |
| | | wsServers.remove(this); |
| | | log.info("客户端未及时发送订阅消息,断开连接"); |
| | | log.info(reason); |
| | | onClose(); |
| | | } |
| | | } |