SpringBoot integrates WebSocket to realize sending messages from the back end to the front end

Table of contents

1. What is websocket interface

2. Applicable scenarios

3. Example code

3.1. Add pom.xml dependency

3.2. Create WebSokcet configuration class

3.3. Create a test sending message interface

3.4. Test webSocket (http://www.jsons.cn/websocket/)


1. What is websocket interface


Using websocket to establish a persistent connection, the server and the client can communicate with each other. As long as the server has data update, it can actively push it to the client.

WebSocket makes data exchange between client and server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a handshake, and a persistent connection can be created directly between the two, and two-way data transmission can be performed.
In the WebSocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server. Data can be directly transmitted between the two.

2. Applicable scenarios

In the process of business development, some asynchronous processing (wechat payment, payment notification of Alipay payment) and cross-application message transmission are encountered.

After the business is executed, the successful information needs to be delivered to the front end. Under normal circumstances, the front end calls the http/https interface of the back end to obtain data. If the back end wants to actively push messages to the front end, it needs to use WebSocket for front-end and back-end communication.

3. Example code

3.1. Add pom.xml dependency

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

3.2. Create WebSokcet configuration class

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
3.3、创建WebSokcet工具类

@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
    private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
 
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
 
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //在线数加1
        addOnlineCount();
        log.info("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            MsgResponseVo userMsgResponseVo = new MsgResponseVo();
            userMsgResponseVo.setMsg("SUCCESS");
            WebSocketServer.sendInfo(JSON.toJSONString(userMsgResponseVo));
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);

        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        log.info(message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

3.3. Create a test sending message interface

 @GetMapping("/testWebSocket")
    public ApiRestResponse testWebSocket() throws IOException {
        //消息体
        MsgResponseVo technicianMsgResponseVo = new MsgResponseVo();
        technicianMsgResponseVo.setRole("Technician");
        technicianMsgResponseVo.setRoleId(1);
        technicianMsgResponseVo.setMsg("您的订单已取消");
        technicianMsgResponseVo.setMsgStatus("CANCEL_ORDER");
        technicianMsgResponseVo.setOrderNo("test");
        //发送消息
        WebSocketServer.sendInfo(JSON.toJSONString(technicianMsgResponseVo));
        return ApiRestResponse.success();
    }
}

3.4. Test webSocket ( http://www.jsons.cn/websocket/ )

Enter the prefix of ws://ip:port/webSocket tool class in the website (ws://127.0.0.1:8080/websocket)

3.5. The front-end uses WebSocket to monitor the back-end WebSocket address, and after receiving the message, do the next step of business processing.

Guess you like

Origin blog.csdn.net/m0_52208135/article/details/127613516