栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot+vue+websocket实现前后端即时通知

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot+vue+websocket实现前后端即时通知

准备 后端引入pom依赖
		
            org.springframework
            spring-websocket
        
前端引入websocket
 npm install --save reconnecting-websocket

在项目结构中的增加域名地址

VUE_APP_DOMAIN = '192.168.0.199:38080'
后端服务搭建 WebSocketServer
@ServerEndpoint(value ="/webSocket/{userId}",encoders = { WebSocketEncoder.class })
@Component
@Data
public class WebSocketServer {
    
    private static AtomicInteger onlineNum = new AtomicInteger();

    
    private static ConcurrentHashMap sessionPools = new ConcurrentHashMap<>();

    
    public static void sendMessage(String msgType,Session session, Object message) throws IOException, EncodeException {
        if (session != null) {
            synchronized (session) {
                if (message instanceof String){
                    session.getBasicRemote().sendObject(Result.success(message).setType("str"));
                }else{
                    session.getBasicRemote().sendObject(Result.success(message).setType(msgType));
                }
            }
        }
    }

    
    public static void sendInfo(String userName, String message) {
        Session session = sessionPools.get(userName);
        try {
            sendMessage(null,session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    @OnOpen
    public static void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            if (ObjectUtil.isNull(userId)){
                sendMessage(null,session, null);
            }else{
                sessionPools.put(userId, session);
                addOnlineCount();
                System.out.println(RedisUtil.getUserName(userId) + "加入webSocket!当前人数为" + onlineNum);
                sendMessage(null,session, "欢迎" + RedisUtil.getUserName(userId) + "加入连接!");
            }
        } catch (IOException | EncodeException e) {
            e.printStackTrace();
        }
    }

    
    @OnClose
    public static void onClose(@PathParam(value = "userId") String userId) {
        sessionPools.remove(userId);
        subOnlineCount();
        System.out.println(RedisUtil.getUserName(userId) + "断开webSocket连接!当前人数为" + onlineNum);
    }

    
    @OnMessage
    public static void onMessage(String message) throws IOException {
        System.out.println(message);
        sessionPools.values().forEach(v->{
            try {
                sendMessage(null,v, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    
    public static void sendByUserIds(String message, List userIds) {
        userIds.forEach(userId->{
            try {
                sendMessage(null, sessionPools.get(userId), message);
            } catch (IOException | EncodeException e) {
                e.printStackTrace();
            }
        });
    }

    
    public static void sendByUserId(String msgType,Object obj, Long userId){
        try {
            sendMessage(msgType, sessionPools.get(String.valueOf(userId)), obj);
        } catch (IOException | EncodeException e) {
            e.printStackTrace();
        }
    }

    
    @OnError
    public static void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

}


WebSocketConfig
@Configuration
public class WebSocketConfig {

    @Bean(name="serverEndpointExporter")
    public ServerEndpointExporter getServerEndpointExporterBean(){
        return new ServerEndpointExporter();
    }
}
WebSocketEncoder
public class WebSocketEncoder implements Encoder.Text {

    @Override
    public String encode(Result object) throws EncodeException {
       if (object.getData() instanceof String){
           return JSONUtil.toJsonStr(object);
       }else{
           BeanWrapper bw = new BeanWrapperImpl(object.getData());
           PropertyDescriptor[] pd = bw.getPropertyDescriptors();
           JSONObject jsonObject = new JSONObject();
           Arrays.stream(pd).filter(f-> ObjectUtil.isNotEmpty(bw.getPropertyValue(f.getName()))).forEach(v->{
               jsonObject.putIfAbsent(v.getName(),bw.getPropertyValue(v.getName())+"");
           });
           JSONObject parseObj = JSONUtil.parseObj(object.getData());
           parseObj.putAll(jsonObject);
           //将java对象转换为json字符串
           return JSONUtil.toJsonStr(object.setData(parseObj));
       }
    }

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }
}

Result
@Data
@Accessors(chain = true)
public class Result {
    
    Integer code;
    
    String msg;
    
    Object data;
    
    String type;

    
    public static Result success(Object data){
        return new Result().setCode(0).setMsg("请求成功").setData(data);
    }

    
    public static Result failed(String msg){
        return new Result().setCode(-1).setMsg(msg);
    }

    
    public static Result get(){
        return new Result();
    }

}

前端webscoket.js
import ReconnectingWebSocket from 'reconnecting-websocket';
import store from '@/store'
import {Notice} from 'iview'
import {seenMessage,getMessageData} from "@/api/data";
import router from "@/router";

export default {
  // 创建 websocket 链接
  createWebsocket(userId) {
    const httpURL = process.env.VUE_APP_DOMAIN;
    this.websocket = new ReconnectingWebSocket(`ws://` + httpURL + `/webSocket/` + userId);
    // 连接发生错误的回调方法
    this.websocket.onerror = this.websocketOnerror;
    // 连接成功建立的回调方法
    this.websocket.onopen = this.websocketOnopen;
    // 接收到消息的回调方法
    this.websocket.onmessage = this.websocketOnmessage;
    // 连接关闭的回调方法
    this.websocket.onclose = this.websocketOnclose;
    // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    this.websocket.onbeforeunload = this.websocketOnbeforeunload;
  },

// 连接发生错误的回调方法
  websocketOnerror() {
    console.log('连接发生错误的回调方法');
  },
// 连接成功建立的回调方法
  websocketOnopen() {

  },
// 接收到消息的回调方法
  websocketOnmessage(event) {
    let obj = JSON.parse(event.data)
    switch (obj.type) {
      case "msg":
        store.commit('setMsgData', obj.data)
        Notice.config({
          duration: 10//消息提示停留10秒
        })
        Notice.info({
          title: obj.data.title,
          name:obj.data.id,
          desc: obj.data.content,
          render: h => {
            return h('span', {
              style: {
                cursor:"pointer"
              },
              on: {
                click: () => {
                  switch (obj.data.msgType) {
                    case 1:
                    case "1":
                      router.push({
                        name: 'activiti-tasks'
                      })
                      break;
                    default:
                      console.log(obj.data)
                      break
                  }
                  seenMessage({id:obj.data.id}).then(res=>{
                    store.commit('setMsgData',[])
                    getMessageData({}).then(res => {
                      if (res.code === '0') {
                        store.commit('setMsgData', res.data)
                        Notice.close(obj.data.id)
                      }
                    })
                  })
                }
              }
          },obj.data.content)
          }
        });
        break;
      default:
        console.log(obj.data)
    }
  },

// 连接关闭的回调方法
  websocketOnclose(event) {
    console.log("连接已关闭")
  },
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常
  websocketOnbeforeunload() {
    this.closeWebSocket();
    console.log('监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常');
  },
// 关闭WebSocket连接
  closeWebSocket() {
    this.websocket.close();
  },
}

前端在初次登录的时候,调用createWebsocket传入用户id,与后端建立连接,后端在调用的时候调用WebSocketServer 中的sendByUserId方法即可

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/914757.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号