Spring 对 WebSocket 提供了强大的支持,能让开发者轻松实现基于 WebSocket 的实时通信应用。下面会详细介绍 Spring 的 WebSocket 支持,并给出实现实时通信的具体步骤。
Spring 的 WebSocket 支持概述
Spring 框架提供了 spring-websocket
和 spring-messaging
模块,借助这些模块可方便地在 Spring 应用里集成 WebSocket 功能。具体支持内容如下:
- 协议支持:支持 WebSocket 协议,能在浏览器和服务器间创建双向通信通道。
- 消息代理:集成了消息代理(如 STOMP),可简化消息的路由与处理。
- 注解驱动:利用注解(如
@MessageMapping
)简化消息处理逻辑的编写。 - SockJS 后备方案:支持 SockJS 协议,当浏览器不支持 WebSocket 时,能自动降级为其他通信方式(如 HTTP 长轮询)。
实现实时通信的步骤
1. 添加依赖
在 pom.xml
中添加必要的依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-messaging</artifactId>
</dependency>
</dependencies>
2. 配置 WebSocket
创建一个配置类来配置 WebSocket 和 STOMP 消息代理:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
上述代码中:
configureMessageBroker
方法用于配置消息代理,enableSimpleBroker
启用了一个简单的内存消息代理,可将消息广播到以/topic
开头的目的地;setApplicationDestinationPrefixes
设置了应用程序的目的地前缀。registerStompEndpoints
方法用于注册 STOMP 端点,addEndpoint("/ws")
注册了一个 WebSocket 端点,withSockJS()
启用了 SockJS 后备方案。
3. 创建消息处理控制器
创建一个控制器类来处理客户端发送的消息:
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String greeting(String message) throws Exception {
return "Hello, " + message + "!";
}
}
这里的 @MessageMapping("/hello")
注解表明该方法会处理来自 /app/hello
目的地的消息,@SendTo("/topic/greetings")
注解则会将方法的返回值广播到 /topic/greetings
目的地。
4. 创建前端页面
创建一个 HTML 页面,使用 STOMP 和 SockJS 库连接到 WebSocket 服务器:
总结
通过以上步骤,你可以在 Spring Boot 应用中实现基于 WebSocket 的实时通信。客户端连接到 WebSocket 服务器,发送消息到 /app/hello
目的地,服务器处理消息后将响应广播到 /topic/greetings
目的地,客户端订阅该目的地并接收消息。