Browse Source

uniapp性能优化:2.以会话为最小单位存储消息

master
xsx 2 years ago
parent
commit
4ceba4cd57
  1. 1
      im-uniapp/App.vue
  2. 6
      im-uniapp/pages/chat/chat-box.vue
  3. 82
      im-uniapp/store/chatStore.js

1
im-uniapp/App.vue

@ -110,7 +110,6 @@
}) })
}, },
handlePrivateMessage(msg) { handlePrivateMessage(msg) {
console.log("handlePrivateMessage")
// //
if (msg.type == enums.MESSAGE_TYPE.LOADING) { if (msg.type == enums.MESSAGE_TYPE.LOADING) {
this.chatStore.setLoadingPrivateMsg(JSON.parse(msg.content)) this.chatStore.setLoadingPrivateMsg(JSON.parse(msg.content))

6
im-uniapp/pages/chat/chat-box.vue

@ -565,13 +565,13 @@
}) })
} }
}, },
loadReaded(fId) { loadReaded(fid) {
this.$http({ this.$http({
url: `/message/private/maxReadedId?friendId=${fId}`, url: `/message/private/maxReadedId?friendId=${fid}`,
method: 'get' method: 'get'
}).then((id) => { }).then((id) => {
this.chatStore.readedMessage({ this.chatStore.readedMessage({
friendId: fId, friendId: fid,
maxId: id maxId: id
}); });
}); });

82
im-uniapp/store/chatStore.js

@ -19,7 +19,8 @@ export default defineStore('chatStore', {
this.chats = []; this.chats = [];
for (let chat of chatsData.chats) { for (let chat of chatsData.chats) {
// 暂存至缓冲区 // 暂存至缓冲区
cacheChats.push(JSON.parse(JSON.stringify(chat))); chat.stored = false;
cacheChats.push(chat);
// 加载期间显示只前15个会话做做样子,一切都为了加快初始化时间 // 加载期间显示只前15个会话做做样子,一切都为了加快初始化时间
if (this.chats.length < 15) { if (this.chats.length < 15) {
chat.messages = []; chat.messages = [];
@ -44,7 +45,6 @@ export default defineStore('chatStore', {
if (chats[idx].type == chatInfo.type && if (chats[idx].type == chatInfo.type &&
chats[idx].targetId === chatInfo.targetId) { chats[idx].targetId === chatInfo.targetId) {
chat = chats[idx]; chat = chats[idx];
chat.delete = false;
// 放置头部 // 放置头部
this.moveTop(idx) this.moveTop(idx)
break; break;
@ -63,7 +63,7 @@ export default defineStore('chatStore', {
messages: [], messages: [],
atMe: false, atMe: false,
atAll: false, atAll: false,
delete: false stored: false
}; };
chats.unshift(chat); chats.unshift(chat);
this.saveToStorage(); this.saveToStorage();
@ -76,7 +76,6 @@ export default defineStore('chatStore', {
} }
}, },
resetUnreadCount(chatInfo) { resetUnreadCount(chatInfo) {
console.log("resetUnreadCount")
let chats = this.curChats; let chats = this.curChats;
for (let idx in chats) { for (let idx in chats) {
if (chats[idx].type == chatInfo.type && if (chats[idx].type == chatInfo.type &&
@ -84,30 +83,31 @@ export default defineStore('chatStore', {
chats[idx].unreadCount = 0; chats[idx].unreadCount = 0;
chats[idx].atMe = false; chats[idx].atMe = false;
chats[idx].atAll = false; chats[idx].atAll = false;
chats[idx].stored = false;
this.saveToStorage();
} }
} }
this.saveToStorage();
}, },
readedMessage(pos) { readedMessage(pos) {
let chats = this.curChats; let chat = this.findChatByFriend(pos.friendId);
for (let idx in chats) { chat.messages.forEach((m) => {
if (chats[idx].type == 'PRIVATE' && if (m.selfSend && m.status < MESSAGE_STATUS.RECALL) {
chats[idx].targetId == pos.friendId) {
chats[idx].messages.forEach((m) => {
if (m.selfSend && m.status != MESSAGE_STATUS.RECALL) {
// pos.maxId为空表示整个会话已读 // pos.maxId为空表示整个会话已读
if (!pos.maxId || m.id <= pos.maxId) { if (!pos.maxId || m.id <= pos.maxId) {
m.status = MESSAGE_STATUS.READED m.status = MESSAGE_STATUS.READED
chats.stored = false;
} }
} }
}) })
} if(!chat.stored){
}
this.saveToStorage(); this.saveToStorage();
}
}, },
removeChat(idx) { removeChat(idx) {
let chats = this.curChats; let chats = this.curChats;
chats.splice(idx, 1); chats[idx].delete = true;
chats[idx].stored = false;
this.saveToStorage(); this.saveToStorage();
}, },
removePrivateChat(userId) { removePrivateChat(userId) {
@ -129,7 +129,6 @@ export default defineStore('chatStore', {
} }
}, },
moveTop(idx) { moveTop(idx) {
console.log("moveTop")
if (this.isLoading()) { if (this.isLoading()) {
return; return;
} }
@ -161,6 +160,7 @@ export default defineStore('chatStore', {
if (msgInfo.type == MESSAGE_TYPE.RECALL) { if (msgInfo.type == MESSAGE_TYPE.RECALL) {
chat.lastContent = msgInfo.content; chat.lastContent = msgInfo.content;
} }
chat.stored = false;
this.saveToStorage(); this.saveToStorage();
return; return;
} }
@ -223,6 +223,7 @@ export default defineStore('chatStore', {
} else { } else {
chat.messages.splice(insertPos, 0, msgInfo); chat.messages.splice(insertPos, 0, msgInfo);
} }
chat.stored = false;
this.saveToStorage(); this.saveToStorage();
}, },
updateMessage(msgInfo) { updateMessage(msgInfo) {
@ -232,6 +233,7 @@ export default defineStore('chatStore', {
if (message) { if (message) {
// 属性拷贝 // 属性拷贝
Object.assign(message, msgInfo); Object.assign(message, msgInfo);
chat.stored = false;
this.saveToStorage(); this.saveToStorage();
} }
}, },
@ -251,6 +253,7 @@ export default defineStore('chatStore', {
break; break;
} }
} }
chat.stored = false;
this.saveToStorage(); this.saveToStorage();
}, },
updateChatFromFriend(friend) { updateChatFromFriend(friend) {
@ -260,6 +263,7 @@ export default defineStore('chatStore', {
// 更新会话中的群名和头像 // 更新会话中的群名和头像
chat.headImage = friend.headImageThumb; chat.headImage = friend.headImageThumb;
chat.showName = friend.nickName; chat.showName = friend.nickName;
chat.stored = false;
this.saveToStorage(); this.saveToStorage();
} }
}, },
@ -270,6 +274,7 @@ export default defineStore('chatStore', {
// 更新会话中的群名称和头像 // 更新会话中的群名称和头像
chat.headImage = group.headImageThumb; chat.headImage = group.headImageThumb;
chat.showName = group.showGroupName; chat.showName = group.showGroupName;
chat.stored = false;
this.saveToStorage(); this.saveToStorage();
} }
}, },
@ -286,7 +291,6 @@ export default defineStore('chatStore', {
} }
}, },
refreshChats(state) { refreshChats(state) {
console.log("refreshChats")
// 排序 // 排序
cacheChats.sort((chat1, chat2) => { cacheChats.sort((chat1, chat2) => {
return chat2.lastSendTime - chat1.lastSendTime; return chat2.lastSendTime - chat1.lastSendTime;
@ -298,22 +302,35 @@ export default defineStore('chatStore', {
this.saveToStorage(); this.saveToStorage();
}, },
saveToStorage(state) { saveToStorage(state) {
console.log("saveToStorage")
// 加载中不保存,防止卡顿 // 加载中不保存,防止卡顿
if (this.isLoading()) { if (this.isLoading()) {
return; return;
} }
const timeStamp = new Date().getTime();
const userStore = useUserStore(); const userStore = useUserStore();
let userId = userStore.userInfo.id; let userId = userStore.userInfo.id;
let key = "chats-app-" + userId; let key = "chats-app-" + userId;
let chatKeys = [];
// 按会话为单位存储,只存储有改动的会话
this.chats.forEach((chat)=>{
let chatKey = `${key}-${chat.type}-${chat.targetId}`
if(chat.delete){
uni.removeStorageSync(chatKey);
return;
}
if(!chat.stored){
uni.setStorageSync(chatKey,chat);
}
chat.stored = true;
chatKeys.push(chatKey);
})
// 会话核心信息
let chatsData = { let chatsData = {
privateMsgMaxId: this.privateMsgMaxId, privateMsgMaxId: this.privateMsgMaxId,
groupMsgMaxId: this.groupMsgMaxId, groupMsgMaxId: this.groupMsgMaxId,
chats: this.chats chatKeys: chatKeys
//chats: this.chats
} }
uni.setStorageSync(key, chatsData) uni.setStorageSync(key, chatsData)
console.log("耗时:", new Date().getTime() - timeStamp);
}, },
clear(state) { clear(state) {
cacheChats = []; cacheChats = [];
@ -325,18 +342,23 @@ export default defineStore('chatStore', {
}, },
loadChat(context) { loadChat(context) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const userStore = useUserStore(); let userStore = useUserStore();
let userId = userStore.userInfo.id; let userId = userStore.userInfo.id;
uni.getStorage({ let chatsData = uni.getStorageSync("chats-app-" + userId)
key: "chats-app-" + userId, if(chatsData){
success: (res) => { if(chatsData.chatKeys){
this.initChats(res.data); let time = new Date().getTime();
resolve() chatsData.chats = [];
}, chatsData.chatKeys.forEach(key=>{
fail: (e) => { let chat = uni.getStorageSync(key);
resolve() if(chat){
chatsData.chats.push(chat);
} }
}); })
}
this.initChats(chatsData);
}
resolve()
}) })
} }
}, },

Loading…
Cancel
Save