小程序聊天,极光 IM 拉取并缓存离线/实时消息

发布时间: 2020-11-05 10:44:58 作者: 大象笔记

背景

由于 ios 和 Android 客户端都集成了极光 IM 的 SDK 来实现用户间聊天功能。 所以,不得不在微信小程序中继续使用极光 SDK。

离线消息拉取并缓存逻辑

两种方案:

所以,我最终选择了第一种方案。

参考 https://community.jiguang.cn/article/306791

app.js 中调用这个封装即可:

  /**
   * 离线消息同步
   **/
  onSyncConversation: function() {
    this.globalData.jim.onSyncConversation(data => {
      console.log(data);
      for (let msg of data) {
        this.cacheMsg(msg, "history")
      }
    });
  },

实时消息监听逻辑

跟离线消息类似,依次写入本地 storage 作为历史消息缓存。

  /**
   * 实时消息监听
   **/
  onMsgReceive: function() {
    this.globalData.jim.onMsgReceive(data => {
      console.log(data);
      this.cacheMsg(data, "realtime")
    });
  },

消息的解析

由于离线消息和实时消息返回的数据结构不一样,并且返回的无用字段比较多,为了节省本地空间,我决定只保留每条消息的三个字段:

storage key 为前缀加发送人 id。

解析缓存逻辑:

  cacheMsg: function(msg, msg_type) {
    let msgs = null;
    let history_username = null;
    if (msg_type == "history") {
      history_username = msg.from_username;
      msgs = msg.msgs;
    } else {
      msgs = msg.messages;
    }

    for (let msg of msgs) {
      let key = null;
      if (msg_type == "history") {
        key = "xxx_con_" + history_username;
      } else {
        key = "xxx_con_" + msg.from_username;
      }
      let historys = wx.getStorageSync(key);
      if (!historys) {
        historys = [];
      }

      historys.push({
        type: msg.content.msg_type,
        body: msg.content.msg_body,
        time: msg.content.create_time,
      })
      wx.setStorageSync(key, historys);
    }
  },

消息缓存空间的上限

同一个微信用户,同一个小程序 storage 上限为 10MB。

参考:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/storage.html

所以有必要对缓存的消息条数做个限制。

建议

如果没有使用极光,强烈不推荐使用极光的小程序 SDK。原因是:

我是一名山东烟台的开发者,联系作者