WebFlux WebSocket 处理器
使用 Spring WebFlux 实现响应式 WebSocket 处理器,以支持非阻塞 I/O。
WebFlux WebSocket 处理器 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Real-Time Systems with Spring 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Reactive WebSockets with WebFlux
Welcome! In this lesson, we'll dive into implementing reactive WebSocket handlers using Spring WebFlux. This approach is key for building high-performance, non-blocking real-time applications.
Spring WebFlux leverages the power of Project Reactor (Flux and Mono) to handle WebSocket connections and messages asynchronously, making your applications highly scalable and efficient.
The WebSocketHandler Interface
At the core of WebFlux WebSockets is the WebSocketHandler interface. It's a functional interface, meaning it has a single abstract method that you'll implement.
This method, handle(WebSocketSession session), is invoked every time a new WebSocket connection is established. It returns a Mono<Void>, signaling when the handling of the session is complete.
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;
// Simplified interface definition
public interface WebSocketHandler {
Mono<Void> handle(WebSocketSession session);
}Implementing a Simple Echo Handler
Let's create a basic Echo Handler. This handler will receive incoming text messages from a client and immediately send them back. It's a fundamental example to demonstrate both receiving and sending reactive messages.
Notice the use of reactive operators like map and flatMap to process the message stream.
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;
public class EchoWebSocketHandler implements WebSocketHandler {
@Override
public Mono<Void> handle(WebSocketSession session) {
// Receive messages, transform them into text messages,
// then send them back to the client.
return session.receive()
.map(WebSocketSession::textMessage)
.flatMap(session::send)
.then(); // Signal completion once the receive stream ends
}
}Understanding WebSocketSession
The WebSocketSession object is crucial. It represents a single, active WebSocket connection with a client. Think of it as your direct line to that specific client.
Key methods of WebSocketSession:
receive(): Returns aFlux<WebSocketMessage>for incoming messages.send(Publisher<WebSocketMessage>): Sends messages to the client.getId(): Provides a unique identifier for the session.textMessage(String payload): Helper to create a text message.
Receiving Messages Reactively
The session.receive() method is how your handler gets incoming messages. It returns a Flux<WebSocketMessage>, which is a stream of messages that arrive over time.
You can apply any of Project Reactor's powerful operators (like doOnNext, filter, map) to process these messages in a non-blocking way.
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;
public class LoggingHandler implements WebSocketHandler {
@Override
public Mono<Void> handle(WebSocketSession session) {
return session.receive()
.doOnNext(message -> {
// Log the received message payload
System.out.println("Received: " + message.getPayloadAsText());
})
.then(); // Ensures the Mono completes when the Flux finishes
}
}Sending Messages Reactively
To send data back to the client, you use session.send(Publisher<WebSocketMessage> messages). This method takes a Publisher (like a Flux or Mono) of messages you want to send.
You can create WebSocketMessage objects using session.textMessage(String payload) for text or session.binaryMessage(DataBuffer payload) for binary data.
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
public class TimeWebSocketHandler implements WebSocketHandler {
@Override
public Mono<Void> handle(WebSocketSession session) {
// Create a Flux that emits a message every second
Flux<WebSocketMessage> messagesToSend = Flux.interval(Duration.ofSeconds(1))
.map(tick -> "Current time: " + System.currentTimeMillis())
.map(session::textMessage); // Convert String to WebSocketMessage
return session.send(messagesToSend);
}
}Configuring WebSocket Endpoints
After creating your WebSocketHandler, you need to register it so Spring WebFlux knows which URL path should map to which handler. This is typically done in a @Configuration class that implements WebSocketConfigurer.
The WebSocketHandlerRegistry allows you to map your handlers to specific paths and configure origins.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.WebSocketConfigurer;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerRegistry;
@Configuration
public class MyWebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// Map the EchoWebSocketHandler to the "/echo" path
registry.addHandler(echoWebSocketHandler(), "/echo").setAllowedOrigins("*");
}
@Bean
public WebSocketHandler echoWebSocketHandler() {
return new EchoWebSocketHandler(); // Your handler instance
}
}Full Server-Side Echo App
Here's a complete, runnable Spring Boot application that combines our WebSocketHandler and its configuration. This creates a functional WebSocket server ready to echo messages!
Run this application, and it will start listening for WebSocket connections on the /echo path.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import org.springframework.web.reactive.socket.server.WebSocketConfigurer;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerRegistry;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class WebFluxEchoServerApplication {
public static void main(String[] args) {
SpringApplication.run(WebFluxEchoServerApplication.class, args);
}
@Configuration
static class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(echoWebSocketHandler(), "/echo").setAllowedOrigins("*");
}
@Bean
public WebSocketHandler echoWebSocketHandler() {
// Inline implementation for simplicity in full example
return new WebSocketHandler() {
@Override
public Mono<Void> handle(WebSocketSession session) {
return session.receive()
.map(WebSocketSession::textMessage)
.flatMap(session::send)
.then();
}
};
}
// Required for WebSocket handling in WebFlux
@Bean
public WebSocketHandlerAdapter handlerAdapter() {
return new WebSocketHandlerAdapter();
}
}
}Connecting with a JavaScript Client
To test your server, you can use a simple JavaScript client in a web browser's developer console. This code connects to your /echo endpoint, sends a message, and logs the response.
Make sure your Spring Boot application is running before attempting to connect!
const socket = new WebSocket('ws://localhost:8080/echo');
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
socket.send('Hello from the client!');
};
socket.onmessage = (event) => {
console.log('Received from server:', event.data);
};
socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};WebFlux Handler Check
You've learned about the core components of WebFlux WebSocket handlers. Let's test your understanding of the main method that initiates session handling.
Recap: WebFlux WebSocket Handlers
Fantastic work! You've successfully explored how to implement reactive WebSocket handlers using Spring WebFlux.
WebSocketHandler: The central interface for defining how to handle new connections.WebSocketSession: Represents a single client connection, providing methods toreceive()andsend()messages.- Reactive Flow: Messages are handled using Project Reactor's
Flux<WebSocketMessage>for incoming streams andPublisher<WebSocketMessage>for outgoing streams. - Configuration: You register your handlers to specific URL paths using a
WebSocketConfigurer.
This reactive approach ensures your real-time applications are scalable, efficient, and robust!
常见问题解答
「WebFlux WebSocket 处理器」课时是免费的吗?
是的 — 「WebFlux WebSocket 处理器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。
「WebFlux WebSocket 处理器」这节课中我会学到什么?
使用 Spring WebFlux 实现响应式 WebSocket 处理器,以支持非阻塞 I/O。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?
无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「WebFlux WebSocket 处理器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 WebSockets & Real-Time Systems with Spring 课中编写并运行代码吗?
能。每节 WebSockets & Real-Time Systems with Spring 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 响应式编程简介
- WebFlux WebSocket 处理器
- 构建响应式实时服务
- 处理响应式流中的背压