WebSocket操作(JAVA SpringBoot)

16 篇文章 0 订阅
1 篇文章 0 订阅

有时候,一些操作需要等待服务器处理完后,前端才能进行下一步操作,所以在这个期间前端必须轮询请求后端查看是否已经处理完毕,但是在高访问量的情况下,轮询可能会造成后端服务器瘫痪,所以这时候可以使用websocket来解决这个问题,通过websocket建立长链接,当后端处理完毕后,通知前端执行下一步操作……

Maven引入

这里引入版本,看情况而定,因为springboot可能已经有对应版本,所以这里可以不写具体版本号

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-websocket</artifactId>

</dependency>

新建配置类

@Configuration

public class WebSocketConfig {

    @Bean

    public ServerEndpointExporter getServerEndpointExporter() {

        return new ServerEndpointExporter();

    }

}

新建请求服务类

@Component

@ServerEndpoint("/webSocket/{oid}")

public class WebSocketServer {

    private static ConcurrentHashMapsessionMap =new ConcurrentHashMap<>();

    /**

    * 前端发送请求建立websocket连接,就会执行@OnOpen方法

    *

    * @param orderId

    * @param session

    */

    @OnOpen

    public void open(@PathParam("oid")String orderId,Session session) {

        sessionMap.put(orderId, session);

        System.out.println("建立websocket连接 orderId:" + orderId);

    }

    /**

    * 前端关闭页面或者主动关闭websocket链接,都会执行@OnClose

    *

    * @param orderId

    */

    @OnClose

    public void close(@PathParam("oid")String orderId) {

        sessionMap.remove(orderId);

        System.out.println("关闭websocket连接 orderId:" + orderId);

    }

    /**

    * 发送数据到前端

    * @param orderId

    * @param msg

    */

    public static void sendMsg(String orderId,String msg) {

        Session session =null;

        try {

            session =sessionMap.get(orderId);

            session.getBasicRemote().sendText(msg);

        }catch (IOException e) {

            e.printStackTrace();

        }

    }

}

在后端controller中,当需要给前端发消息时,进行如下调用

WebSocketServer.sendMsg(orderId,"2"); //这里的调用了WebSocketServer 类中的sendMsg方法,这里的2是定义的一个状态,用于前端判断之用

前端页面操作

可在页面载入需要执行的JS方法中写如下代码

//前端发送websocket连接请求

let webSocketUrl = webSocketBaseUrl + "webSocket/" + this.orderInfo.orderId;

var websocket = new WebSocket(webSocketUrl);

websocket.onmessage = function(event){

    let msg = event.data;

    if(msg == "2"){  //根据后端传过来的数据进行判断

         //下面则是具体操作业务

        $("#payQrcodeDiv").html("<label style='font-size:20px; color:green'>订单支付完成!</label>");

    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值