SpringBoot进行消息推送的的几种方式

Spring Boot进行消息推送的几种方式包括:

  1. WebSocket

  2. SockJS

  3. STOMP

  4. Server-Sent Events (SSE)

  5. Push Notifications

以下是WebSocket的案例代码:

  1. 添加WebSocket依赖

    org.springframework.boot
    spring-boot-starter-websocket

  1. 创建WebSocket配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/myHandler");
    }

    @Bean
    public WebSocketHandler myHandler() {
        return new MyWebSocketHandler();
    }
}
  1. 创建WebSocket处理器
public class MyWebSocketHandler extends TextWebSocketHandler {

    private static final Set sessions = new HashSet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        for (WebSocketSession s : sessions) {
            s.sendMessage(message);
        }
    }
}
  1. 发送消息
@Controller
public class HomeController {

    @MessageMapping("/send")
    @SendTo("/topic/myTopic")
    public String sendMessage(String message) {
        return message;
    }
}
  1. 接收消息
var socket = new WebSocket('/myHandler');

socket.onmessage = function(message) {
    console.log(message.data);
}

这是一个最基本的WebSocket示例,实际上WebSocket可以实现更复杂的功能,需要根据具体的需求进行配置和实现。

你可能感兴趣的:(spring,boot,后端,java)