项目总结48:Springboot集成Websocket案例

Posted wobuchifanqie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了项目总结48:Springboot集成Websocket案例相关的知识,希望对你有一定的参考价值。

项目总结48:Springboot集成Websocket案例

 

Springboot集成Websocket的具体实现由很多方式,但原理是一样的;

先放一个具体的案例

  pom.xml jar依赖

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

   服务端发送消息

package com.hs.web.thirdparty.webconnect;

import com.hs.common.util.json.JsonUtil;

import java.util.ArrayList;
import java.util.List;


public class WebConnectionManager {

    private static WebConnectionManager instance = new WebConnectionManager();

    private List<UpdateListener> changeListenerList;

    private WebConnectionManager() {
        changeListenerList = new ArrayList<UpdateListener>();
    }

    public static WebConnectionManager getInstance() {
        return instance;
    }

    public void addChangeListener(UpdateListener changeListener) {
        synchronized (changeListenerList) {
            changeListenerList.add(changeListener);
        }
    }
    
    public void removeChangeListener(UpdateListener changeListener) {
        synchronized (changeListenerList) {
            for (UpdateListener listener : changeListenerList) {
                if (listener.getUid().equals(changeListener.getUid())) {
                    changeListenerList.remove(listener);
                    break;
                }
            }
        }
    }

    public void sendMessage(String message) {
        synchronized (changeListenerList) {
            for (UpdateListener listener : changeListenerList) {
                listener.updateHandle(message);
            }
        }
    }
    
    public void sendMessage(Object obj) {
        //System.out.println("JsonUtil.toJson(obj): " +JsonUtil.toJson(obj));
        sendMessage(JsonUtil.toJson(obj));
    }

    private String getMessage() {
        return null;
    }
    
    public static void main(String[] args) {
    }
    

}

   客户端请求入口

package com.hs.web.thirdparty.webconnect;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.logging.Logger;

@ServerEndpoint(value = "/monitor")
@Component
public class WebSocketServer {
    
    private Session targetSession;
    private UpdateListener changeListener;
    private static final Logger sysLogger = Logger.getLogger("sysLog");

    /**
     *@Description:链接建立成功时调用的方法
     *@param
     *@return  void
     *@author  TangYujie
     *@date  2019/12/12 17:11
     */
    @OnOpen
    public void open(Session session) {
        this.targetSession = session;
        
        changeListener = new UpdateListener() {
            
            @Override
            public String getUid() {
                return targetSession.getId();
            }
            
            @Override
            public void updateHandle(String message) {
                sendMessage(message);
            }
        };
        
        WebConnectionManager.getInstance().addChangeListener(changeListener);
        sysLogger.info("*** WebSocket opened from sessionId " + targetSession.getId());
    }

    /**
     *@Description:收到客户端消息
     *@param
     *@return  void
     *@author  TangYujie
     *@date  2019/12/12 17:13
     */
    @OnMessage
    public void inMessage(String message) {

    }

    /**
     *@Description: 连接关闭
     *@param
     *@return  void
     *@author  TangYujie
     *@date  2019/12/12 17:15
     */
    @OnClose
    public void end() {
        WebConnectionManager.getInstance().removeChangeListener(changeListener);
        sysLogger.info("*** WebSocket closed from sessionId " + this.targetSession.getId());
    }
    
    private synchronized void sendMessage(String message){
        try {
            targetSession.getBasicRemote().sendText(message);
        } catch (IOException e) {
            sysLogger.warning(e.getMessage());
        } catch(IllegalStateException e){
            sysLogger.warning(e.getMessage());
        }
    }
    

}

  监听接口类:一个接口类,定义了updateHandle(数据库处理)和getUid(获取Uid)两个方法

package com.hs.web.thirdparty.webconnect;

public interface UpdateListener {
    
    void updateHandle(String message);
    
    String getUid();

}

  服务端发送消息

    public static void main(String[] args) {
        String data = "this is a test message";
        WebConnectionManager.getInstance().sendMessage(data);
    }

 

 

分析说明:

  1-当客户端通过ws://ip:port/monitor连接socket时,根据@ServerEndpoint(value = "/monitor")注解;执行WebSocketServer 标有@OnOpen的open方法,即建立一个连接;

  2-open方法中会实现一个UpdateListener 接口类,并将该实现加入到WebConnectionManager 中的List<UpdateListener> changeListenerList中;而UpdateListener 接口类中的updateHandle实现了targetSession.getBasicRemote().sendText(message);即服务端的消息推送;

  3-当服务端通过WebConnectionManager.getInstance().sendMessage(data)发送消息时,会遍历List<UpdateListener> changeListenerList,执行其中的updateHandle方法,从而进行消息推送;

以上是关于项目总结48:Springboot集成Websocket案例的主要内容,如果未能解决你的问题,请参考以下文章

RocketMQ 集成 SpringBoot

RocketMQ 集成 SpringBoot

RocketMQ 集成 SpringBoot

RocketMQ 集成 SpringBoot

Springboot集成Kafka

个人项目实战3,springboot集成mybatis分页插件