WebSocket的使用(消息推送)

1.引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.配置类

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter getServerEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

3.业务方法

@Component
@ServerEndpoint("/webSocket/{oid}")
public class WebSocketService {
    private static ConcurrentHashMap<String,Session> sessionMap = new ConcurrentHashMap<>();
    /**
     * 前端发送请求建立WebSocket连接就会执行@OnOpen方法
     */
    @OnOpen
    public void open(@PathParam("oid")String orderId, Session session){
        sessionMap.put(orderId,session);
    }
    /**
     * 前端关闭页面或者主动关闭webSocket连接,都会执行close
     */
    @OnClose
    public void close(@PathParam("oid")String orderId){
        sessionMap.remove(orderId);
    }

    //封装的发送消息方法
    public static void  sendMessage(String orderId,String message){
        try {
            Session session = sessionMap.get(orderId);
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

当需要向前端推送消息时调用sendMessage方法根据orderId拿到session发送消息

4.前端发送连接请求和前端接收请求

// 前端发送websocket连接请求
					var websocket = null;
					var webSocketUrl =  webSocketBaseUrl +"webSocket/" + this.orderInfo.orderId;
					websocket = new WebSocket(webSocketUrl);
					// 只要后端通过websocket向此连接发送消息就会触发onmessage事件
					websocket.onmessage = function(event){
						console.log(event)
						var msg = event.data;
						if(msg == "1"){
							$("#div1").html("<label style='font-size:20px; color:green'>订单支付完成!</label>")
						}

					}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值