最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot業(yè)務功能實戰(zhàn)之告別輪詢websocket的集成使用

 更新時間:2022年10月21日 11:26:41   作者:小鮑侃java  
WebSocket使得客戶端和服務器之間的數(shù)據(jù)交換變得更加簡單,允許服務端主動向客戶端推送數(shù)據(jù),下面這篇文章主要給大家介紹了關于springboot業(yè)務功能實戰(zhàn)之告別輪詢websocket的集成使用,需要的朋友可以參考下

后端代碼

首先加入pom文件

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

加入配置類

@Configuration
public class WebSocketConfig {
 
    /**
     * 	注入ServerEndpointExporter,
     * 	這個bean會自動注冊使用了@ServerEndpoint注解聲明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

加入連接發(fā)送消息方法

@Component
@ServerEndpoint("/websocket/{userName}")
// 此注解相當于設置訪問URL
public class WebSocket {
 
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();
    private final static Logger logger = LoggerFactory.getLogger(LoginIntercept.class);
 
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userName") String userName) {
        this.session = session;
        webSockets.add(this);
        if (sessionPool.containsKey(userName)) {
            sessionPool.put(userName + String.valueOf(session.getId()), session);
        } else {
            sessionPool.put(userName, session);
        }
        logger.info("【websocket消息】有新的連接,總數(shù)為:" + webSockets.size());
    }
 
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        logger.info("【websocket消息】連接斷開,總數(shù)為:" + webSockets.size());
    }
 
    @OnMessage
    public void onMessage(String message) {
        logger.info("【websocket消息】收到客戶端消息:" + message);
    }
 
    /**
     * 功能描述: 此為廣播消息
     *
     * @param: [message] (消息)
     * @return: void ()
     */
    public void sendAllMessage(String message) {
        for (WebSocket webSocket : webSockets) {
            logger.info("【websocket消息】廣播消息:" + message);
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 功能描述:此為單點消息 (發(fā)送文本) 現(xiàn)在可以發(fā)送給多客戶端
     *
     * @param: [userName, message] (接收人,發(fā)送消息)
     * @return: void ()
     */
    public void sendTextMessage(String userName, String message) {
        // 遍歷sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在當前用戶
            if (key.toString().indexOf(userName) != -1) {
                Session session = sessionPool.get(key);
                if (session != null && session.isOpen()) {
                    try {
                        session.getAsyncRemote().sendText(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
 
    /**
     * 功能描述: 此為單點消息 (發(fā)送文本) 現(xiàn)在可以發(fā)送給多客戶端
     *
     * @param: [userName, message] (接收人,發(fā)送消息)
     * @return: void ()
     */
    public void sendObjMessage(String userName, Object message) {
        // 遍歷sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在當前用戶
            if (key.toString().indexOf(userName) != -1) {
                Session session = sessionPool.get(key);
                if (session != null && session.isOpen()) {
                    try {
                        session.getAsyncRemote().sendObject(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

發(fā)送信息

@RestController
@RequestMapping("websocket")
public class WebSocketController {
 
    @GetMapping("setMessage")
    @ApiOperation(value = "發(fā)送信息接口", notes = "發(fā)送信息接口")
    public Result
        webSocket(@ApiParam(name = "定時任務日志實體", value = "定時任務日志實體", required = false) @RequestBody MessageVO messageVO) {
        Result result = new Result();
        String userName = messageVO.getUserName();
        String message = messageVO.getMessage();
        WebSocket webSocket = new WebSocket();
        webSocket.sendTextMessage(userName, message);
        return result;
    }
}

前段代碼

import sysConfig from "../config";
import {Notification} from 'element-ui';
import {EVENT_TYPE} from "../const";
export function openSocket(userId) {
  let ws = new WebSocket(`${sysConfig.SOCKET_URL}/${userId}`);
  // let ws = new WebSocket(`ws://121.40.165.18:8800`);
  ws.onopen = function (evt) {
    Notification({
      title: '歡迎回來!',
      message: `${sysConfig.SOCKET_URL}/${userId}`
    });
  };
  ws.onmessage = function (e) {
    console.log(typeof e.data);
    try{
      if(e.data!=undefined || e.data!=null){
        let json= JSON.parse(e.data);
        Notification({
          title: json.messageTitle,
          message: json.messageText
        });
        //通知頁面更新
        window.postMessage(EVENT_TYPE.updateMessage,'/');
      }
    }catch(err){
        console.log("webSocke異常,異常信息:"+err)
    }
 
 
    //ws.close();
  };
  ws.onclose = function (evt) {
    console.log('Connection closed.');
  };
}

總結(jié)

到此這篇關于springboot業(yè)務功能實戰(zhàn)之告別輪詢websocket集成使用的文章就介紹到這了,更多相關springboot websocket的集成使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

云南省| 沿河| 四平市| 永城市| 武汉市| 淮安市| 革吉县| 邛崃市| 馆陶县| 瓦房店市| 茂名市| 万安县| 平昌县| 彭阳县| 井陉县| 天津市| 克山县| 神农架林区| 长寿区| 敦化市| 天祝| 密云县| 林周县| 托克托县| 即墨市| 昌图县| 伊宁市| 游戏| 理塘县| 临沂市| 聂荣县| 宁都县| 崇礼县| 兴城市| 襄城县| 达孜县| 鄂伦春自治旗| 永胜县| 和田县| 宁波市| 民勤县|