Spring Boot进行消息推送的几种方式包括:
-
WebSocket
-
SockJS
-
STOMP
-
Server-Sent Events (SSE)
-
Push Notifications
以下是WebSocket的案例代码:
- 添加WebSocket依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 创建WebSocket配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(myHandler(), "/myHandler");}@Beanpublic WebSocketHandler myHandler() {return new MyWebSocketHandler();}
}
- 创建WebSocket处理器
public class MyWebSocketHandler extends TextWebSocketHandler {private static final Set<WebSocketSession> sessions = new HashSet<>();@Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {sessions.add(session);}@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {sessions.remove(session);}@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {for (WebSocketSession s : sessions) {s.sendMessage(message);}}
}
- 发送消息
@Controller
public class HomeController {@MessageMapping("/send")@SendTo("/topic/myTopic")public String sendMessage(String message) {return message;}
}
- 接收消息
var socket = new WebSocket('/myHandler');socket.onmessage = function(message) {console.log(message.data);
}
这是一个最基本的WebSocket示例,实际上WebSocket可以实现更复杂的功能,需要根据具体的需求进行配置和实现。