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

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

 更新時(shí)間:2022年10月21日 11:26:41   作者:小鮑侃java  
WebSocket使得客戶端和服務(wù)器之間的數(shù)據(jù)交換變得更加簡(jiǎn)單,允許服務(wù)端主動(dòng)向客戶端推送數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于springboot業(yè)務(wù)功能實(shí)戰(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,
     * 	這個(gè)bean會(huì)自動(dòng)注冊(cè)使用了@ServerEndpoint注解聲明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

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

@Component
@ServerEndpoint("/websocket/{userName}")
// 此注解相當(dāng)于設(shè)置訪問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();
            }
        }
    }
 
    /**
     * 功能描述:此為單點(diǎn)消息 (發(fā)送文本) 現(xiàn)在可以發(fā)送給多客戶端
     *
     * @param: [userName, message] (接收人,發(fā)送消息)
     * @return: void ()
     */
    public void sendTextMessage(String userName, String message) {
        // 遍歷sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在當(dāng)前用戶
            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();
                    }
                }
            }
        }
    }
 
    /**
     * 功能描述: 此為單點(diǎn)消息 (發(fā)送文本) 現(xiàn)在可以發(fā)送給多客戶端
     *
     * @param: [userName, message] (接收人,發(fā)送消息)
     * @return: void ()
     */
    public void sendObjMessage(String userName, Object message) {
        // 遍歷sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在當(dāng)前用戶
            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 = "定時(shí)任務(wù)日志實(shí)體", value = "定時(shí)任務(wù)日志實(shí)體", 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é)

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

相關(guān)文章

最新評(píng)論

遂昌县| 扎囊县| 石棉县| 皋兰县| 嘉兴市| 浦东新区| 娄烦县| 溆浦县| 晋宁县| 泾源县| 云和县| 罗源县| 平湖市| 景谷| 承德县| 舟山市| 房产| 石河子市| 大丰市| 山西省| 隆化县| 罗甸县| 和龙市| 饶河县| 丽江市| 达拉特旗| 天津市| 客服| 双流县| 襄汾县| 合肥市| 长寿区| 吴旗县| 牙克石市| 望城县| 遂宁市| 万宁市| 温泉县| 方正县| 辽中县| 闻喜县|