Spring Boot Websocket Simple Broker Sample
by 개발자   2024-02-08 13:26:36   조회수:471


1. Dependencies:


XML

<dependencies>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-websocket</artifactId>

    </dependency>

</dependencies>


2. Configuration:


Enable WebSocket message handling with @EnableWebSocketMessageBroker annotation.

Configure the simple broker using enableSimpleBroker(). Specify destinations clients can subscribe to (e.g., /topic).

Java

@SpringBootApplication

@EnableWebSocketMessageBroker

public class MyApplication {


    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);

    }


    @Configuration

    public static class WebSocketConfig implements WebSocketMessageBrokerConfigurer {


        @Override

        public void configureMessageBroker(MessageBrokerRegistry registry) {

            registry.enableSimpleBroker("/topic");

        }

    }

}


3. Controller:


Create a controller with a method to send messages to subscribed clients.

Use SimpMessagingTemplate to send messages with destinations.

Java

@Controller

public class GreetingController {


    @Autowired

    private SimpMessagingTemplate messagingTemplate;


    @GetMapping("/hello")

    public String greeting() {

        return "hello";

    }


    @PostMapping("/send")

    public void sendMessage(@RequestBody String message) {

        messagingTemplate.convertAndSend("/topic/greetings", message);

    }

}


4. JavaScript Client:


Include STOMP client library.

Connect to the WebSocket endpoint.

Subscribe to destinations and handle received messages.

HTML

<!DOCTYPE html>

<html>

<head>

    <title>WebSocket Chat</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.7.9/stomp.min.js"></script>

</head>

<body>

    <input type="text" id="message">

    <button onclick="sendMessage()">Send</button>

    <div id="messages"></div>

    <script>

        // ... (code to connect, subscribe, and handle messages)

    </script>

</body>

</html>


5. Running the application:


Start the Spring Boot application.

Access the /hello endpoint in your browser.

Implement the JavaScript client-side logic to connect, subscribe, and send/receive messages.

Remember:


This is a basic example. You can customize it further for real-time messaging applications.

For production use, consider using a dedicated message broker (e.g., RabbitMQ, ActiveMQ) instead of the simple broker.

Additional Resources:


Spring WebSockets Getting Started: https://www.baeldung.com/websockets-spring

STOMP Protocol: https://stomp.github.io/

Spring Boot WebSockets with STOMP: https://www.toptal.com/java/stomp-spring-boot-websocket