【经验分享】SpringBoot集成WebSocket开发02 之 实现一个基本示例并Spring Bean注入的方式来组织代码

发布于:2025-03-18 ⋅ 阅读:(13) ⋅ 点赞:(0)

结合Spring Boot和WebSocket实现一个基本示例,并且使用Spring Bean注入的方式来组织代码。

1. 创建Spring Boot项目

首先,确保你有一个Spring Boot项目,并在pom.xml文件中引入了WebSocket相关的依赖。

<dependencies>
    <!-- Spring Boot WebSocket -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>

    <!-- Spring Boot Starter Web for Rest Controllers -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Starter for Logging and other utilities -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
</dependencies>

2. WebSocket 配置类

创建一个配置类,启用WebSocket支持,并且在这个类中配置一个TextWebSocketHandler来处理消息的传递。

import org.springframework.context.annotation.Configuration;
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.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final MyWebSocketHandler myWebSocketHandler;

    // 注入自定义的 WebSocketHandler
    public WebSocketConfig(MyWebSocketHandler myWebSocketHandler) {
        this.myWebSocketHandler = myWebSocketHandler;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myWebSocketHandler, "/ws").setAllowedOrigins("*");
    }
}

3. 创建自定义WebSocketHandler

MyWebSocketHandler 类继承自TextWebSocketHandler,用来处理WebSocket消息的接收和发送。我们将使用Spring的@Component注解让这个类成为一个Spring Bean,并通过构造器注入来引入服务逻辑。

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    private final MyService myService;

    // 构造器注入MyService
    public MyWebSocketHandler(MyService myService) {
        this.myService = myService;
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 通过MyService处理消息
        String response = myService.processMessage(message.getPayload());
        try {
            // 发送处理后的消息
            session.sendMessage(new TextMessage(response));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4. 创建一个简单的Service

我们创建一个简单的Service类MyService,用来处理消息的业务逻辑。它会被注入到MyWebSocketHandler中。

import org.springframework.stereotype.Service;

@Service
public class MyService {

    public String processMessage(String message) {
        // 这里是消息处理的业务逻辑,可以根据实际需要修改
        return "处理后的消息: " + message;
    }
}

5. 创建Controller(可选)

如果你想通过HTTP请求来访问WebSocket服务,或者提供一个WebSocket客户端连接的页面,你可以创建一个简单的Controller。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WebSocketController {

    @GetMapping("/ws")
    public String hello() {
        return "WebSocket 服务正在运行";
    }
}

6. 启动应用

创建Application类来启动Spring Boot应用:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebSocketApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebSocketApplication.class, args);
    }
}

7. 测试WebSocket连接

使用WebSocket客户端(例如浏览器控制台、Postman、WebSocket客户端插件等)连接到ws://localhost:8080/ws,并发送一些消息。你应该能收到由MyService处理后的消息。

例如,发送消息"Hello WebSocket",应该会收到类似 "处理后的消息: Hello WebSocket" 的响应。


说明:

  • WebSocketConfig中,我们将MyWebSocketHandler注册为WebSocket处理器,并指定WebSocket的URL /ws
  • 通过构造器注入,MyWebSocketHandler可以访问Spring管理的MyService Bean,并在WebSocket连接中调用它处理消息。
  • MyService封装了消息的业务逻辑,保持了代码的清晰与解耦。

这个示例展示了Spring Boot与WebSocket的基本集成,同时也体现了如何使用Spring的依赖注入来组织代码。