What is the @EnableWebSocketMessageBroker annotation in Spring Boot, its principle, and how to use it

What is the @EnableWebSocketMessageBroker annotation in Spring Boot, its principle, and how to use it

WebSocket is a technology for two-way communication between a web browser and a web server. In traditional HTTP communication, the client sends a request to the server, the server responds to the request, and then closes the connection. In WebSocket, the connection between the client and the server is always open, and messages can be sent to each other at any time to achieve real-time communication.

Spring Boot provides support for WebSocket, and the WebSocket message broker function can be quickly enabled through the @EnableWebSocketMessageBroker annotation. This article will introduce the principle and usage of @EnableWebSocketMessageBroker.

insert image description here

What is the @EnableWebSocketMessageBroker annotation

@EnableWebSocketMessageBroker is an annotation in the Spring Framework to enable the WebSocket message broker function. This annotation can be used in Spring Boot applications to enable applications to support WebSocket communication.

principle

The principle of the @EnableWebSocketMessageBroker annotation is to support WebSocket communication by configuring a message broker. Before using the @EnableWebSocketMessageBroker annotation, you must first define a WebSocket configuration class and mark the class as a configuration class with the @Configuration annotation.

In the WebSocket configuration class, you need to use the @EnableWebSocketMessageBroker annotation to enable the WebSocket message broker function. This annotation automatically configures a WebSocketMessageBrokerConfigurer instance and registers it with the Spring application context.

WebSocketMessageBrokerConfigurer is an interface for configuring WebSocket message brokers in the Spring framework. By implementing this interface, you can configure the relevant parameters of the WebSocket message agent, such as the address of the message agent, message type, thread pool for sending and receiving messages, etc.

After enabling the WebSocket message broker, you can use the @MessageMapping annotation to define the processing method of the WebSocket message. The @MessageMapping annotation is used to specify the address of the WebSocket request. When the client sends a request to this address, it will automatically call the corresponding processing method for processing.

how to use

Let's demonstrate how to use the @EnableWebSocketMessageBroker annotation and related annotations to implement WebSocket communication.

Step 1: Add dependencies

Before using @EnableWebSocketMessageBroker, you need to add the following dependencies to your project:

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

Step 2: Define the WebSocket configuration class

Define a WebSocket configuration class in the project to configure the relevant parameters of the WebSocket message broker. The specific code is as follows:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
    
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    
    
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
    
    
        registry.addEndpoint("/ws").withSockJS();
    }
}

The configuration class uses the @EnableWebSocketMessageBroker annotation to enable the WebSocket message broker function, uses the configureMessageBroker method to configure the relevant parameters of the message broker, and uses the registerStompEndpoints method to register the WebSocket endpoint of the Stomp protocol.

In the configureMessageBroker method, we use the enableSimpleBroker method to configure the address of the message broker. Here we set the address of the message broker to "/topic", which means that all messages starting with "/topic" will be routed to the message broker. The setApplicationDestinationPrefixes method is used to set the destination prefix of the application, here we set it to "/app", which means that all messages starting with "/app" will be routed to the controller.

In the registerStompEndpoints method, we use the addEndpoint method to add the WebSocket endpoint, here we set the WebSocket endpoint to "/ws", and use the withSockJS method to enable SockJS support for communication on browsers that do not support WebSocket.

Step 3: Define the WebSocket Controller

Define a WebSocket controller in the project to process WebSocket messages. The specific code is as follows:

@Controller
public class WebSocketController {
    
    
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
    
    
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " +message.getName() + "!");
    }
}

The controller uses the @MessageMapping annotation to define the address of the WebSocket request. Here we set the request address to "/hello", which means that when the client sends a request to this address, the greeting method will be automatically called for processing. The @SendTo annotation is used to specify the address of the WebSocket response, and when the processing method returns a response, the response will be automatically sent to this address.

In the greeting method, we simulate a 1-second delay through the Thread.sleep method and return a Greeting object containing the greeting.

Step 4: Write the front-end code

Finally, we need to write the front-end code to communicate with the WebSocket. Here, we have used SockJS and Stomp.js to implement WebSocket communication. The specific code is as follows:

var stompClient = null;

function connect() {
    
    
    var socket = new SockJS('/ws');
    stompClient = Stomp.over(socket);
    stompClient.connect({
    
    }, function(frame) {
    
    
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings', function(greeting) {
    
    
            showGreeting(JSON.parse(greeting.body).content);
        });
    });
}

function disconnect() {
    
    
    if (stompClient !== null) {
    
    
        stompClient.disconnect();
    }
    console.log("Disconnected");
}

function sendName() {
    
    
    var name = $("#name").val();
    stompClient.send("/app/hello", {
    
    }, JSON.stringify({
    
     'name': name }));
}

function showGreeting(message) {
    
    
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
    
    
    $("form").on('submit', function (e) {
    
    
        e.preventDefault();
    });
    $("#connect").click(function() {
    
     connect(); });
    $("#disconnect").click(function() {
    
     disconnect(); });
    $("#send").click(function() {
    
     sendName(); });
});

In the above code, we first define a connect function to create a WebSocket connection. After the connection is successful, we use the subscribe method to subscribe to the "/topic/greetings" address. When a message arrives, the showGreeting method will be automatically called to display the message.

In the sendName function, we send a message to the "/app/hello" address through the stompClient.send method, which contains an attribute named "name", whose value is the name entered by the user.

Finally, after the page has loaded, we use jQuery to register event listeners to call the relevant functions when the user clicks the button.

Summarize

The @EnableWebSocketMessageBroker annotation is an annotation used to enable the WebSocket message broker function in Spring Boot. WebSocket communication can be realized by configuring a message broker and defining a WebSocket controller. In practical applications, we can use SockJS and Stomp.js to simplify the development of WebSocket communication.

Guess you like

Origin blog.csdn.net/2301_77835649/article/details/131481644