WebSocketConfig.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package top.haijunit.websocket.config;
  2. import cn.hutool.core.util.StrUtil;
  3. import lombok.RequiredArgsConstructor;
  4. import org.springframework.boot.autoconfigure.AutoConfiguration;
  5. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  6. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.web.socket.WebSocketHandler;
  10. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  11. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  12. import org.springframework.web.socket.server.HandshakeInterceptor;
  13. import top.haijunit.websocket.config.properties.WebSocketProperties;
  14. import top.haijunit.websocket.handler.CustomWebSocketHandler;
  15. import top.haijunit.websocket.handler.WebSocketTopicListener;
  16. /**
  17. * @author zhanghaijun
  18. * @date 2023/11/17 17:47
  19. * @description [一句话描述该类的功能]
  20. */
  21. @AutoConfiguration
  22. @EnableConfigurationProperties(WebSocketProperties.class)
  23. @EnableWebSocket
  24. @RequiredArgsConstructor
  25. public class WebSocketConfig {
  26. private final ApplicationContext applicationContext;
  27. @Bean
  28. public WebSocketConfigurer webSocketConfigurer(HandshakeInterceptor handshakeInterceptor, WebSocketHandler webSocketHandler, WebSocketProperties webSocketProperties) {
  29. if (StrUtil.isBlank(webSocketProperties.getPath())) {
  30. webSocketProperties.setPath("/websocket");
  31. }
  32. if (StrUtil.isBlank(webSocketProperties.getAllowedOrigins())) {
  33. webSocketProperties.setAllowedOrigins("*");
  34. }
  35. return registry -> registry.addHandler(webSocketHandler, webSocketProperties.getPath()).addInterceptors(handshakeInterceptor).setAllowedOrigins(webSocketProperties.getAllowedOrigins());
  36. }
  37. @Bean
  38. public HandshakeInterceptor handshakeInterceptor() {
  39. return new top.haijunit.websocket.handler.WebSocketInterceptor();
  40. }
  41. @Bean
  42. public WebSocketHandler webSocketHandler() {
  43. return new CustomWebSocketHandler(applicationContext);
  44. }
  45. @Bean
  46. public WebSocketTopicListener topicListener() {
  47. return new top.haijunit.websocket.handler.WebSocketTopicListener();
  48. }
  49. }