vue+springboot+websocket实现消息通知,含应用场景

这篇具有很好参考价值的文章主要介绍了vue+springboot+websocket实现消息通知,含应用场景。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

vue、springboot

实现场景

image.png
点击同步之后更新数据,更新时间比较长,因此使用异步,之后该按钮置灰,在数据更新完成之后,服务端通知客户端已经同步成功,通知提示框,用户即可查看数据
image.png

前端
1、在对应的页面编写初始化、连接成功,错误,接受信息方法
// 初始化方法
init() {

  //1、websocket接口的url
      let ws =
        "http://localhost:21204/ws/platofrmAsync/" +
        this.$store.state.user.userId;

      // 实例化socket
      this.socket = new WebSocket(ws);
      // 监听socket连接
      this.socket.onopen = this.socketopen;
      // 监听socket错误信息
      this.socket.onerror = this.error;
      // 监听socket消息
      this.socket.onmessage = this.getMessage;
      // 监听socket断开连接的消息
      this.socket.close = this.close;
    },

// 连接成功方法
    socketopen() {
      console.log("socket连接成功");
    },
// 连接错误
    error() {
      console.log("连接错误");
    },
// 接受信息接口
    getMessage(message) {
      console.log("收到消息");
      //当接受到信息之后,就可以做后续的处理了
      let data = JSON.parse(message.data);
      this.$notify({
        title: "消息通知",
        type: "success",
        message: "平台【" + data.platformName + "】已经资源树同步完成",
        position: "bottom-right",
      });
      this.getList();
    },
// 关闭处理
    close() {
      console.log("连接关闭");
    },
2、mounted或者created方法中启动初始化方法
  mounted() {
    this.init();
  },
后端
1、配置ServerEndpointExporter
package com.eshore.framework.config.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    /**
     * 这个Bean的作用是自动注册使用了@ServerEndpoint注解的Bean
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

2、编写ServerEndpoint
package com.eshore.web.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * author:walker
 * time: 2023/6/28
 * description:  平台同步
 */
@Component
@Slf4j
// 类似于controlelr 服务点
@ServerEndpoint(value = "/ws/platofrmAsync/{userId}")
public class PlatformAsyncWebSocket {

    // 用来存储每一个客户端对象对应的WsController对象
    private static Map<String, PlatformAsyncWebSocket> onlineUsers = new ConcurrentHashMap<>();
    // 声明Session对象,通过该对象可以给指定的用户发送请求
    private Session session;

    /**
     * 连接建立时被调用
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        log.info("连接成功");
        // 将局部的session对象赋值给成员session对象
        this.session = session;
        // 这里是因为前端在传数据的时候,会将userId传过来
        //所以使用将userId和websocket对象存储起来,方便下次服务端推送信息的时候使用
        Map<String, List<String>> requestParameterMap = this.session.getRequestParameterMap();
        List<String> userIds = requestParameterMap.get("userId");
        String userId = userIds.get(0);
        onlineUsers.put(userId, this);

    }

    /**
     * 接收到客户端消息时被调用
     */
    @OnMessage
    public void onMessage(String message, Session session) {
    	
    }

    /**
     * 连接被关闭时调用
     */
    @OnClose
    public void onClose(Session session) {
        //关闭时则将map中的用户移除
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
        List<String> userIds = requestParameterMap.get("userId");
        String userId = userIds.get(0);
        onlineUsers.remove(userId);
    }


    //推送消息
    //将消息推送给某个指定的用户
    public void sendMsg(String userId, String message) {
        try {
            PlatformAsyncWebSocket wsController = onlineUsers.get(userId);
            wsController.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("用户{} 发送信息{}失败", userId, message);
            e.printStackTrace();
        }

    }


}

3、编写测试服务端推送方法
package com.eshore.web.controller.test;

import com.alibaba.fastjson.JSON;
import com.eshore.biz.domain.BizPlatformInfo;
import com.eshore.web.websocket.PlatformAsyncWebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class WebsocketTest {

    @Autowired
    private PlatformAsyncWebSocket platformAsyncWebSocket;

    @GetMapping("/send/{userId}")
    public void testWsSend(@PathVariable(value = "userId") String userId){
        BizPlatformInfo bizPlatformInfo = new BizPlatformInfo();
        bizPlatformInfo.setId(1L);
        bizPlatformInfo.setPlatformName("平台AA");
        platformAsyncWebSocket.sendMsg(userId, JSON.toJSONString(bizPlatformInfo));
    }

}

测试

1、首先前端进入对应的页面,就会出现连接成功
image.png

2、调用测试方法
image.png
之后就可以看到 通知成功的信息了
image.png文章来源地址https://www.toymoban.com/news/detail-514977.html

到了这里,关于vue+springboot+websocket实现消息通知,含应用场景的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java使用websocket实现消息实时通知

    博客仅做学习记录使用。 做项目中遇到这样一个实时通知需求,因为第一次接触这个,期间查了很多资料,看了很多博客,最后实现功能,查询的博客太多,就不一一放出来了,感谢各位大佬。 websocket方式主要代码来源于这个大佬的博客: https://blog.csdn.net/moshowgame/article/d

    2024年02月08日
    浏览(30)
  • 【HarmonyOS】消息通知场景的实现

                从今天开始,博主将开设一门新的专栏用来讲解市面上比较热门的技术 “鸿蒙开发”,对于刚接触这项技术的小伙伴在学习鸿蒙开发之前,有必要先了解一下鸿蒙,从你的角度来讲,你认为什么是鸿蒙呢?它出现的意义又是什么?鸿蒙仅仅是一个手机操作系

    2024年01月17日
    浏览(18)
  • uniapp通过websocket实现手机APP通知栏消息显示功能(前端部分)

     开门见山地说,在移动应用端,从后端及时获取消息,展示到手机消息通知栏上面来与用户进行交互是一个很高频的应用场景,这篇文章就来介绍一下,在uniapp开发中如何实现这种需求。  要实现这个需求,对于前端来说主要技术需要拆分成两部分:一是从后端及时获取消

    2024年03月18日
    浏览(56)
  • SSE与WebSocket分别实现服务器发送消息通知(Golang、Gin)

    服务端推送,也称为消息推送或通知推送,是一种允许应用服务器主动将信息发送到客户端的能力,为客户端提供了实时的信息更新和通知,增强了用户体验。 服务端推送的背景与需求主要基于以下几个诉求: 实时通知:在很多情况下,用户期望实时接收到应用的通知,如

    2024年02月03日
    浏览(29)
  • uni-app使用plus本地推送通知栏信息,不使用第三方个推实现消息在线统一推送、消息通知(MQTT、WebSocket、setInterval定时器)

    plus.push.createMessage() 因项目一直是运行在内网,所以不支持使用uni-push等运行在公网的第三方个推渠道。 那就只能使用 plus.push.createMessage() ,示例代码如下: 参数解释: content : ( String 类型) 必选,消息显示的内容,在系统通知中心中显示的文本内容。 payload : ( String 类型 ) 可

    2024年02月15日
    浏览(25)
  • 服务端(后端)主动通知前端的实现:WebSocket(springboot中使用WebSocket案例)

    我们都知道 http 协议只能浏览器单方面向服务器发起请求获得响应,服务器不能主动向浏览器推送消息。想要实现浏览器的主动推送有两种主流实现方式: 轮询:缺点很多,但是实现简单 websocket:在浏览器和服务器之间建立 tcp 连接,实现全双工通信 springboot 使用 websocket 有

    2023年04月14日
    浏览(44)
  • JAVA 使用WebSocket发送通知消息

    注: 1、jdk必须要1.8及以上 2、项目若有接口拦截过滤,WebSocket接口必须要配置拦截,使其可以验证通过 WebSocket 业务类 发送消息的方法 前端代码

    2024年02月11日
    浏览(26)
  • SpringBoot整合调用微信模板方法实现微信公众号消息通知推送,Java实现微信公众号给关注用户推送自定义消息通知(手把手从0到1)

    目录 概述 公众号给关注用户推送自定义消息 一、申请公众号模板消息 二、获取安装“web开发者工具” 三、微信网页授权说明 四、微信网页授权 - 流程时序图 五、HTTPClient 实现微信公众号消息推送与发布(四步走) 六、通过weixin-java-mp SDK实现微信公众号消息推送与发布(七

    2024年02月10日
    浏览(21)
  • 【通用消息通知服务】0x3 - 发送我们第一条消息(Websocket)

    项目地址: A generic message notification system[Github] Websocket Connection Pool Websocket Provider websocket接口 结果截图

    2024年02月10日
    浏览(20)
  • SpringBoot+Netty+Websocket实现消息推送

    这样一个需求:把设备异常的状态每10秒推送到页面并且以弹窗弹出来,这个时候用Websocket最为合适,今天主要是后端代码展示。 添加依赖 定义netty端口号 netty服务器 Netty配置 管理全局Channel以及用户对应的channel(推送消息) 管道配置 自定义CustomChannelHandler 推送消息接口及

    2024年02月04日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包