将 WebSockets 集成到 Spring
在 Spring Boot 应用中配置 WebSocket 支持,为订阅启用持久的客户端-服务器连接。
将 WebSockets 集成到 Spring 是 CoddyKit 上的免费 GraphQL APIs with Spring Boot 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 GraphQL APIs with Spring Boot 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 GraphQL APIs with Spring Boot 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
WebSockets for Real-time Data
Welcome! In this lesson, we'll integrate WebSockets with Spring Boot. This is crucial for enabling real-time features like GraphQL Subscriptions.
WebSockets provide a persistent, two-way communication channel between a client and a server over a single, long-lived TCP connection.
Why WebSockets for Subscriptions?
Unlike traditional HTTP requests (which are short-lived), GraphQL Subscriptions require a continuous connection to push data updates to clients as they happen.
WebSockets are the perfect fit because they maintain an open connection, allowing the server to send data to the client at any time without a new request.
Adding the Dependency
First, we need to add the Spring Boot WebSocket starter dependency to our project. This brings in all the necessary libraries to enable WebSocket support.
For Gradle, add this to your build.gradle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-websocket'
}Enabling WebSocket Message Broker
In Spring, we use annotations to enable specific functionalities. For WebSockets with a message broker, we use @EnableWebSocketMessageBroker.
This annotation enables a STOMP over WebSocket message broker, which is a powerful way to handle messaging.
Configuring WebSocket Endpoints
We need a configuration class that extends WebSocketMessageBrokerConfigurer. This class allows us to customize our WebSocket setup.
The registerStompEndpoints() method is used to define the URL endpoint clients will connect to for WebSocket communication.
Adding SockJS Fallback
When registering an endpoint, we often add .withSockJS(). SockJS is a JavaScript library that provides a WebSocket-like API.
It offers fallback options (like HTTP streaming or long polling) for browsers that don't fully support WebSockets or in environments with proxies that interfere.
Configuring the Message Broker
The configureMessageBroker() method sets up the message broker itself. This defines how messages are routed between clients and the application.
enableSimpleBroker("/topic"): Enables an in-memory message broker for destinations prefixed with/topic. Clients subscribe to these topics.setApplicationDestinationPrefixes("/app"): Defines prefixes for messages destined for methods annotated with@MessageMappingin our application.
Complete WebSocket Configuration
Here's a minimal Spring Boot application demonstrating the WebSocket configuration. Try running it to see Spring initialize the WebSocket server!
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
System.out.println("WebSocket server ready on port 8080!");
System.out.println("Connect at ws://localhost:8080/ws-connect");
}
@Configuration
@EnableWebSocketMessageBroker
static class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws-connect")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
}
}Bridging to GraphQL Subscriptions
With this WebSocket infrastructure, our GraphQL subscription resolvers (from the previous lesson) can now publish events.
When a resolver publishes an event, Spring's message broker ensures that all clients subscribed to the relevant /topic are immediately notified via their open WebSocket connection.
Quick Check: WebSocket Config
Consider the following line from our WebSocket configuration:
config.enableSimpleBroker("/topic");What is the primary purpose of the /topic prefix in this context?
Recap: WebSockets in Spring
Great job! You've learned how to integrate WebSockets with Spring Boot to provide a robust real-time communication layer.
- We added the WebSocket starter dependency.
- We used
@EnableWebSocketMessageBrokerandWebSocketMessageBrokerConfigurer. - We configured STOMP endpoints (e.g.,
/ws-connectwith SockJS). - We set up a message broker with prefixes like
/topicfor subscriptions and/appfor app-specific messages.
This setup is the foundation for delivering real-time GraphQL Subscriptions!
常见问题解答
「将 WebSockets 集成到 Spring」课时是免费的吗?
是的 — 「将 WebSockets 集成到 Spring」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 GraphQL APIs with Spring Boot 课程的其余内容,请升级到 CoddyKit PRO。 GraphQL APIs with Spring Boot 课程共包含 4 节课。
「将 WebSockets 集成到 Spring」这节课中我会学到什么?
在 Spring Boot 应用中配置 WebSocket 支持,为订阅启用持久的客户端-服务器连接。 你通过在浏览器中直接运行的动手代码来练习 GraphQL APIs with Spring Boot,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 GraphQL APIs with Spring Boot 需要有经验吗?
无需任何先前经验。CoddyKit 上的 GraphQL APIs with Spring Boot 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「将 WebSockets 集成到 Spring」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 GraphQL APIs with Spring Boot 课中编写并运行代码吗?
能。每节 GraphQL APIs with Spring Boot 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 理解 GraphQL 订阅
- 实现实时更新
- 将 WebSockets 集成到 Spring
- 订阅的过滤与扩展