package top.haijunit.websocket.config; import cn.hutool.core.util.StrUtil; import lombok.RequiredArgsConstructor; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.server.HandshakeInterceptor; import top.haijunit.websocket.config.properties.WebSocketProperties; import top.haijunit.websocket.handler.CustomWebSocketHandler; import top.haijunit.websocket.handler.WebSocketTopicListener; /** * @author zhanghaijun * @date 2023/11/17 17:47 * @description [一句话描述该类的功能] */ @AutoConfiguration @EnableConfigurationProperties(WebSocketProperties.class) @EnableWebSocket @RequiredArgsConstructor public class WebSocketConfig { private final ApplicationContext applicationContext; @Bean public WebSocketConfigurer webSocketConfigurer(HandshakeInterceptor handshakeInterceptor, WebSocketHandler webSocketHandler, WebSocketProperties webSocketProperties) { if (StrUtil.isBlank(webSocketProperties.getPath())) { webSocketProperties.setPath("/websocket"); } if (StrUtil.isBlank(webSocketProperties.getAllowedOrigins())) { webSocketProperties.setAllowedOrigins("*"); } return registry -> registry.addHandler(webSocketHandler, webSocketProperties.getPath()).addInterceptors(handshakeInterceptor).setAllowedOrigins(webSocketProperties.getAllowedOrigins()); } @Bean public HandshakeInterceptor handshakeInterceptor() { return new top.haijunit.websocket.handler.WebSocketInterceptor(); } @Bean public WebSocketHandler webSocketHandler() { return new CustomWebSocketHandler(applicationContext); } @Bean public WebSocketTopicListener topicListener() { return new top.haijunit.websocket.handler.WebSocketTopicListener(); } }