SpringBoot整合WebSocket服务 springboot整合websocket springboot使用websocket springboot使用websocket
在Spring Boot中整合WebSocket服务,你可以使用Spring的@EnableWebSocketMessageBroker
注解来配置一个WebSocket消息代理。以下是一个简单的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 配置WebSocket消息代理:
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 registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
- 创建一个控制器来处理WebSocket请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebSocketController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String greeting(String message) {
return "Hello, " + message + "!";
}
}
在上述配置中,客户端可以通过/ws
端点连接到WebSocket服务。服务端通过/app/hello
路径接收消息,并通过@SendTo
注解将消息广播到所有订阅了/topic/greetings
的客户端。
确保你的Spring Boot应用程序有一个启动类,并且已经配置了必要的组件扫描,以便Spring能够发现上述配置的WebSocket组件。
评论已关闭