我们使用spring-boot接入websocket有三种方式:使用 @EnableWebSocket @EnableWebSocketMessageBroker 以及 @ServerEndpoint ,本文主要介绍使用 @ServerEndpoint 方式的流程以及碰到的问题解决

添加依赖
确保 spring-boot-starter-websocket 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

定义@ServerEndpoint类
这个是核心类方法,可以在这里定义生命周期方法(比如onOpenonMessage等)

//定义成spring bean
@Component
@Slf4j
//定义websocket路径,这里的configurator后面再讲解
@ServerEndpoint(value = "/wss/conn/{cookieValue}",configurator = WebSocketConfigurator.class)
public class WebSocketServer {
    //业务的spring bean注入
    private static TestWrapper testWrapper;
   //静态set注入spring bean
    @Autowired
    public void setTestWrapper(TestWrapper testWrapper) {
        WebSocketServer.testWrapper = testWrapper;
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接建立: " + session.getId());
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot
为什么要用WebSocket?
为了在做一些操作后,服务端能主动向客户端提示失败结果,而HTTP协议只能是客户端向服务端发送请求。
而WebSocket就是一个基于TCP的新协议,类似于socket.io;
在服务端和客户端之间建立socket链接以便服务端进行主动推送。
pom.xml配置:
        <dep...
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpoi
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketConfig
 *  * blog.coder4j.cn
				
### 如何在Spring Boot项目中集成WebSocket 为了在Spring Boot项目中集成WebSocket,在`pom.xml`文件里添加必要的依赖项是必需的操作。具体来说,应该引入`spring-boot-starter-websocket`来支持WebSocket功能。 ```xml <dependencies> <!-- WebSocket support --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- For JSON message handling with STOMP over WebSocket --> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator-core</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>sockjs-client</artifactId> <version>1.5.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>stomp-websocket</artifactId> <version>2.3.4</version> </dependency> </dependencies> 上述代码片段展示了如何通过Maven管理器为Spring Boot应用程序增加对WebSocket的支持[^1]。除了基本的WebSocket启动器外,还包含了用于处理JSON消息以及实现STOMP协议(简单文本定向消息协议)所必需的一些WebJars库。这些额外组件有助于简化前端与后端之间的通信过程。 对于希望利用更高级特性的开发者而言,还可以考虑加入其他相关依赖,比如: - `spring-boot-starter-security`: 如果计划保护WebSocket连接免受未经授权访问的影响; - `spring-session-data-redis`: 当需要跨多实例部署时保持会话状态的一致性。 值得注意的是,随着版本更新,某些特定版本号可能不再适用最新版Spring Boot,请参照官方文档获取最准确的信息并调整相应设置。
Could not find an appender,Did you define it below instead of above in the configuration file? 31316