Springboot超仔细整合websocket(附案例代码)
以下是一个简单的Spring Boot应用程序,用于演示如何整合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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class WebSocketController {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String greeting(String message) {
return "Hello, " + message + "!";
}
@RequestMapping("/send")
@ResponseBody
public String sendMessage(String message) {
simpMessagingTemplate.convertAndSend("/topic/greetings", "Hello, " + message + "!");
return "Message sent";
}
}
这个例子中,我们定义了一个WebSocket端点/ws
,并且配置了一个简单的消息代理/topic
。greeting
方法处理客户端发送到/app/hello
的消息,并将处理后的消息广播到/topic/greetings
。sendMessage
方法允许通过/send
接口发送消息,它实际上与greeting
方法做了同样的事情。
这个例子展示了如何在Spring Boot应用程序中设置WebSocket,并处理简单的消息。在实际应用中,你可能需要添加额外的安全配置,或者处理更复杂的业务逻辑。
评论已关闭