SpringBoot集成WebSocket支持流式消息推送

背景

在日常工作中,经常遇到需要前后端消息交互的场景,例如

  • 客服软电话,需要通知前端弹出工作台。
  • 业务异常报警,提醒用户及时关注。
  • 用户账户余额不足,提醒其及时充值。
  • 持续向用户推送应用日志等等。

以上场景,自然而然就需要webSocket支持。 而且,需要支持单条消息推送,也要支撑流式消息推送。废话不多说,开搞!

一、后端使用SpringBoot集成Websocket。

1.引入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.创建WebsocketServerEndpoint。

说明:由于spring默认单例,这里需要用集合记录Endpoint。

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author Doit
 * @Date 2022/8/21 10:25
 * @Desc websocket server
 * @Version 1.0
 * @Slogan Just do it.
 */

@Slf4j
@Component
@ServerEndpoint("/doit/websocket/{target}") //创建ws的请求路径。
public class WebsocketServerEndpoint {
    private Session session;
    private String target;
    //支持持续流推送
    private InputStream inputStream;
    private final static CopyOnWriteArraySet<WebsocketServerEndpoint> websockets = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session , @PathParam("target") String target){
        this.session = session;
        this.target = target;
        websockets.add(this);
        log.info("websocket connect server success , target is {},total is {}",target,websockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("message is {}",message);
    }

    @OnClose
    public void onClose(){
        log.info("connection has been closed ,target is {},total is {}" ,this.target, websockets.size());
        this.destroy();
    }

    @OnError
    public void onError(Throwable throwable){
        this.destroy();
        log.info("websocket connect error , target is {} ,total is {}, error is {}",this.target ,websockets.size(),throwable.getMessage());
    }

    /**
     * 根据目标身份推送消息
     * @param target
     * @param message
     * @throws IOException
     */
    public void sendMessageOnce(String target, String message) throws IOException {
        this.sendMessage(target,message,false,null);
    }

    /**
     * stream 同步日志输出,通过websocket推送至前台。
     * @param target
     * @param is
     * @throws IOException
     */
    public void sendMessageSync(String target, InputStream is) throws IOException {
        this.sendMessage(target,null,true , is);
    }

    /**
     * Send message.
     * @param target 通过target获取{@link WebsocketServerEndpoint}.
     * @param message message
     * @param continuous 是否通过inputStream持续推送消息。
     * @param is 输入流
     * @throws IOException
     */
    private void sendMessage(String target , String message ,Boolean continuous , InputStream is) throws IOException {
        WebsocketServerEndpoint websocket = getWebsocket(target);
        if(Objects.isNull(websocket)){
            throw new RuntimeException("The websocket does not exists or has been closed.");
        }
        if(continuous){
            if(Objects.isNull(is)){
                throw new RuntimeException("InputStream can not be null when continuous is true.");
            }else{
                websocket.inputStream = is;
                CompletableFuture.runAsync(websocket::sendMessageWithInputSteam);
            }
        }else{
            websocket.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 通过inputStream 持续推送消息。
     * 支持文件、消息、日志等。
     */
    private void sendMessageWithInputSteam(){
        String message;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(this.inputStream));
        try {
            while ((message = bufferedReader.readLine()) !=null){
                if(websockets.contains(this)){
                    this.session.getBasicRemote().sendText(message);
                }
            }
        }catch(IOException e){
            log.warn("SendMessage failed {}",e.getMessage());
        }finally {
            this.closeInputStream();
        }
    }

    /**
     * 根据目标获取对应的{@link WebsocketServerEndpoint}。
     * @param target 约定标的
     * @return WebsocketServerEndpoint
     */
    private WebsocketServerEndpoint getWebsocket(String target){
        WebsocketServerEndpoint websocket = null;
        for (WebsocketServerEndpoint ws : websockets) {
            if (target.equals(ws.target)) {
                websocket = ws;
            }
        }
        return websocket;
    }

    /**
     * close inputStream.
     * @Author Doit
     * @Date 20221/08/23 15:30:00
     */
    private void closeInputStream(){
        if(Objects.nonNull(inputStream)){
            try {
                inputStream.close();
            } catch (Exception e) {
                log.warn("websocket close failed {}",e.getMessage());
            }
        }
    }

    /**
     * destroy {@link WebsocketServerEndpoint}
     * @Author Doit
     * @Date 20221/08/23 15:30:00
     */
    private void destroy(){
        websockets.remove(this);
        this.closeInputStream();
    }
}

3.创建Configuration,把WebsocketServerEndpoint交给SpringBoot作支持。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @Author Doit
 * @Date 2022/8/21 10:25
 * @Desc websocket configuration
 * @Version 1.0
 * @Slogan Just do it.
 */
@Configuration
public class WebsocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

此时,后段内容已完成。

4.前端采用SocketJS,帮你解决浏览器兼容问题,推荐使用。

<script src="./socket.js"></script>
<script>
    //@ServerEndpoint 里的地址。 ws用于http,wss用于https,后者更安全。
    var ws = new WebSocket("ws//127.0.0.1:10881/doit/websocket/{target}");
    //建立连接
    ws.onopen = function(msg) {
        console.log("Connection open ...");
    };
    //发送消息
    ws.onmessage = function(msg) {
        console.log("Received msg: " + msg.data);
    };
    //关闭连接
    ws.onclose = function(msg) {
        console.log("Connection closed.");
        ws.close();
    };
    ws.onerror = function(msg){
        console.log("Connection error.");
        ws.close();
    };
</script>

5.开发完成,可以快乐的单机使用了。

  1. 首先通过target约定身份建立ws,一般采用请求方IP组合用户ID的方式。
  2. 通过接口推送消息,支持sendOnce 和 sendWithInputStream,分别用来支持单次推送和流式推送(如日志等)。

后记

以上内容仅供单机玩玩,生产使用需要集群方案。后续有进阶方案,欢迎关注。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
Spring Boot中,可以通过使用Server-Sent Events(SSE)技术来实现流式输出。SSE是一种基于HTTP的服务端推送技术,它允许服务器向客户端发送单向的数据流,这些数据可以是文本、JSON等数据格式。 下面是一个使用Spring Boot SSE实现流式输出的示例代码: 首先,在Spring Boot应用程序中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> ``` 然后,创建一个RESTful控制器,该控制器使用SSE技术向客户端输出数据。以下是一个简单的控制器示例: ```java @RestController public class MyController { @GetMapping("/stream") public Flux<String> stream() { return Flux.interval(Duration.ofSeconds(1)) .map(seq -> "Stream - " + seq); } } ``` 在上面的示例中,我们使用`@GetMapping`注解将一个路由绑定到`/stream`路径。当客户端连接到此路由时,控制器将使用`Flux`对象返回数据流。在这种情况下,我们使用`Flux.interval()`方法创建一个每秒发送一次消息的数据流。 最后,在客户端中,可以使用JavaScript代码来订阅SSE事件并接收数据。以下是一个简单的JavaScript代码示例: ```javascript const source = new EventSource('/stream'); source.onmessage = function(event) { console.log(event.data); }; ``` 在上面的示例中,我们使用`EventSource`对象来订阅`/stream`路径上的SSE事件。当事件被触发时,回调函数将被调用,并显示接收到的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农的散文诗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值