基于spring boot+nettey-socket實(shí)現(xiàn)長(zhǎng)連接消息實(shí)時(shí)推送

gradle導(dǎo)入相關(guān)包:

compile group: 'com.corundumstudio.socketio', name: 'netty-socketio', version: '1.7.7'

消息監(jiān)聽類

import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletContextEvent; 
import javax.servlet.ServletContextListener; 
import javax.servlet.annotation.WebListener;

@Configuration 
@WebListener 
public class SocketioLisener implements ServletContextListener { 

@Autowired 
private Socketio socketio;
@Override
public void contextInitialized(ServletContextEvent sce) {
    //啟動(dòng)Socketio服務(wù)
    socketio.startServer();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
    //關(guān)閉Socketio服務(wù)
    Socketio socketio = new Socketio();
    socketio.stopSocketio();
}

}

事件定義類

import com.corundumstudio.socketio.Configuration; 
import com.corundumstudio.socketio.SocketIOClient; 
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener; 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.stereotype.Component; 
import org.springframework.stereotype.Service;
import java.util.Collection;

@Service 
public class Socketio { 
private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Value("${socket.server.host}")
private String host;

@Value("${socket.server.port}")
private int port;

private static SocketIOServer socketIOServer;

/**
 * @Title: startSocketio
 * @Description: 創(chuàng)建服務(wù)添加客戶端
 */
public void startSocketio() {

    // 配置
    Configuration conf = new Configuration();
    // 指定要主機(jī)ip地址,這個(gè)和頁(yè)面請(qǐng)求ip地址一致
    conf.setHostname(host);
    // 指定端口號(hào)
    conf.setPort(port);

    socketIOServer = new SocketIOServer( conf );

    ConnectListener connect = new ConnectListener() {
        @Override
        public void onConnect( SocketIOClient client ) {
            logger.info("客戶端連接成功,sessionId={}",client.getSessionId());
            client.sendEvent("helloPush", "hello");
        }
    };
    // 添加客戶端
    socketIOServer.addConnectListener( connect );
    socketIOServer.start();
}

/**
 * @Description: 全體消息推送
 * @param type
 *  前臺(tái)根據(jù)類型接收消息,所以接收的消息類型不同,收到的通知就不同 推送的事件類型
 * @param content
 *  推送的內(nèi)容
 */
public void pushMessage( String type, Object content ) {

    // 獲取全部客戶端
    Collection<SocketIOClient> allClients = socketIOServer.getAllClients();
    for( SocketIOClient socket : allClients ) {
        socket.sendEvent( type, content );
        logger.info("Socket推送消息成功 sessionId={},事件名稱=={},message={}",socket.getSessionId(),type,content);
    }
}

/**
 * @Title: startServer
 * @Description: 啟動(dòng)服務(wù)
 */
public void startServer() {
    if( socketIOServer == null ) {
        new Thread( new Runnable() {

            @Override
            public void run() {

                startSocketio();
            }
        } ).start();
    }
}

/**
 * 暫時(shí)不用
 * @Title: stopSocketio
 * @Description: 停止服務(wù)
 */
public void stopSocketio() {
    if( socketIOServer != null ) {
        socketIOServer.stop();
        socketIOServer = null;
    }
}
}

業(yè)務(wù)類調(diào)用[全體消息推送]

try {
    Socketio socketio = new Socketio();
    //這里發(fā)送的消息內(nèi)容可以結(jié)合具體場(chǎng)景自定義對(duì)象
    String message =  "下午2點(diǎn)開大會(huì)啦";
    socketio.pushMessage("mining_msg", message);
} catch (Exception e) {
    logger.error("后推送即時(shí)消息失敗,e={}",e);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容