LotWebSocketHandler.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package cn.hobbystocks.auc.websocket;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.web.socket.CloseStatus;
  6. import org.springframework.web.socket.WebSocketSession;
  7. import org.springframework.web.socket.handler.TextWebSocketHandler;
  8. import java.net.URI;
  9. import java.util.concurrent.ConcurrentHashMap;
  10. import java.util.concurrent.ConcurrentMap;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13. @Component
  14. @Slf4j
  15. public class LotWebSocketHandler extends TextWebSocketHandler {
  16. private static final Pattern LOT_PATH_PATTERN = Pattern.compile(".*/(?:bid/)?ws/lot/(\\d+)$");
  17. private final LotWebSocketSessionRegistry sessionRegistry;
  18. private final ConcurrentMap<String, Long> sessionLots = new ConcurrentHashMap<>();
  19. @Autowired
  20. public LotWebSocketHandler(LotWebSocketSessionRegistry sessionRegistry) {
  21. this.sessionRegistry = sessionRegistry;
  22. }
  23. @Override
  24. public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  25. Long lotId = resolveLotId(session.getUri());
  26. if (lotId == null) {
  27. session.close(CloseStatus.BAD_DATA);
  28. return;
  29. }
  30. sessionLots.put(session.getId(), lotId);
  31. sessionRegistry.register(lotId, session);
  32. }
  33. @Override
  34. public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
  35. Long lotId = sessionLots.remove(session.getId());
  36. if (lotId != null) {
  37. sessionRegistry.unregister(lotId, session);
  38. }
  39. }
  40. static Long resolveLotId(URI uri) {
  41. if (uri == null) {
  42. return null;
  43. }
  44. Matcher matcher = LOT_PATH_PATTERN.matcher(uri.getPath());
  45. if (!matcher.matches()) {
  46. return null;
  47. }
  48. return Long.valueOf(matcher.group(1));
  49. }
  50. }