【SpringBoot学习】43、SpringBoot 使用 Uniapp 集成 Websocket 实现消息推送

SpringBoot 使用 Uniapp 集成 Websocket 实现消息推送

1、SpringBoot 配置

(1)依赖配置

导入依赖,一样的 stater,这里就不多概述了

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

(2)Websocket 配置

websocket 的配置

package com.ruoyi.business.common.websocket;

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

/**
 * websocket的配置
 *
 * @author Tellsea
 * @date 2022/4/26
 */
@Configuration
public class WebSocketConfig {

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

WebSocket 服务端

package com.ruoyi.business.common.websocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

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

/**
 * WebSocket 服务
 *
 * @author Tellsea
 * @date 2022/4/26
 */
@Slf4j
@Component
@ServerEndpoint("/open/webSocket/{userId}")
public class WebSocketServer {

    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    /**
     * 连接建立成
     * 功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //加入set中
            webSocketMap.put(userId, this);
        } else {
            //加入set中
            addOnlineCount();
            webSocketMap.put(userId, this);
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 连接关闭
     * 调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
        //log.info("收到客户端消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        /*if (StringUtils.isNotBlank(message)) {
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId", this.userId);
                String toUserId = jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
                    webSocketMap.get(toUserId).sendMessage(message);
                } else {
                    //否则不在这个服务器上,发送到mysql或者redis
                    log.error("请求的userId:" + toUserId + "不在该服务器上");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
    }


    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送自定义消息
     **/
    public static void sendInfo(String userId, String message) {
        log.info("发送消息到:" + userId + ",报文:" + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("用户" + userId + ",不在线!");
        }
    }

    /**
     * 获得此时的
     * 在线人数
     *
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人
     * 数加1
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    /**
     * 在线人
     * 数减1
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

(3)测试控制层

package com.ruoyi.business.common.websocket;

import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.ApiOperation;
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;

/**
 * @author Tellsea
 * @date 2022/4/26
 */
@RestController
@RequestMapping("/open/webSocket")
public class WebSocketController {

    @ApiOperation("测试通讯")
    @GetMapping("/test/{userId}/{message}")
    public AjaxResult test(@PathVariable("userId") String userId, @PathVariable("message") String message) {
        WebSocketServer.sendInfo(userId, message);
        return AjaxResult.success("发送成功");
    }
}

请求地址/open 开头,是配置了权限拦截放开

(4)服务端业务主动发送消息

需要推送消息的地方使用 sendMessage 带用户 ID 的方法即可

// 推送消息
        WebSocketServer.sendInfo(String.valueOf(storeInfo.getStoreUserId()), "您有新的职工订单,请及时配送");

2、Uniapp 配置

登录成功,初始化连接 websocket,退出的时候,也需要关闭 websocket,要不然推送消息接收不到

 request.connectionWebSocket();

封装的方法,其中 onSocketOpen 中有一个 setInterval 定时器 sendSocketMessage 发送消息到服务端,因为 websocket 默认时间为一分钟就会自动断开连接,所以需要实时通讯,保证 websocket 是在线状态

缓存中存放的 webSocketOnLine 状态,是在页面上显示消息是否在线的判断依据,页面定时获取这个状态显示在页面上即可,即实时更新消息状态是否在线

/**
 * 连接 WebSocket
 */
function connectionWebSocket() {
    let user = uni.getStorageSync(config.cachePrefix + 'user');
    if (validator.isEmpty(user)) {
        return;
    }
    //连接
    uni.connectSocket({
        url: config.wsUrl + user.userId,
    });
    //打开websocket回调
    uni.onSocketOpen(function (res) {
        uni.setStorageSync(config.cachePrefix + 'webSocketOnLine', true);
        showMsg('消息连接成功');
        //每隔5秒钟发送一次心跳,避免websocket连接因超时而自动断开
        setInterval(function () {
            uni.sendSocketMessage({
                data: '心跳检测'
            });
        }, 5 * 1000);
    });
    //连接失败回调
    uni.onSocketError(function (res) {
        uni.setStorageSync(config.cachePrefix + 'webSocketOnLine', false);
        showMsg('消息连接失败');
    });
    //关闭websocket打印
    uni.onSocketClose(function (res) {
        uni.setStorageSync(config.cachePrefix + 'webSocketOnLine', false);
        showMsg('消息连接已关闭');
    });
    //服务端过来内容之后打印
    uni.onSocketMessage(function (res) {
        console.log(res);
        showMsg(res.data);
        speekText(res.data);
    });
}

退出系统或者关闭界面时,需要关闭 websocket,要不然即使用户 ID 在线,也接收不到消息

uni.closeSocket();

3、生产环境 Nginx 配置

生产环境部署,websocket 必须加上代理配置,这样 Nginx 才能正确转发 websocket 的通讯

		location /project-service {
			# websocket 必须加上的配置
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection "upgrade";
		}

如果你的服务器是通过 https 访问的, 则 websocket 访问地址同样也需要从 ws 修改为 wss

	baseUrl: 'http://192.168.3.6:8080/project-service',
	wsUrl: 'ws://192.168.3.6:8080/project-service/open/webSocket/',

上面两个配置,在服务器开启了 https 的前提下,需要讲 http 修改为 https,wx 修改为 wss

到此 SpringBoot 使用 Uniapp 集成 Websocket 实现消息推送,OK

微信公众号

  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
uniapp极光推送使用uniapp框架开发应用时,集成极光推送功能的一种方法。具体步骤如下: 1. 首先需要在极光推送平台创建应用。进入【服务中心】-【开发者平台】,点击【概览】- 【创建应用】,填写应用名称和图标。 2. 选择【消息推送】服务,并进行下一步操作。 3. 设置应用包名,并进行下一步操作。在设置页面可以查看AppKey和Master Secret,这些信息在后续的配置中会用到。 4. 安装和配置uniapp极光插件,根据插件的使用指南进行安装和配置。 5. 配置完成后,可以在手机上进行测试,如果配置成功,就可以收到推送通知。需要注意的是,这种属于“控制台”推送,如果需要使用后台的“API”推送功能,需要进行后端的配置。 总结起来,uniapp极光推送的配置包括创建应用、设置应用信息、安装和配置插件等步骤。通过这些步骤,就可以实现uniapp应用中集成极光推送功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [uniApp消息推送(极光/阿里云)](https://blog.csdn.net/qq_44930306/article/details/129085708)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [uniapp+极光做消息推送](https://blog.csdn.net/weixin_45449046/article/details/121270014)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tellsea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值