1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
| class MessageService { constructor(databaseService, cacheService) { this.db = databaseService; this.cache = cacheService; }
async sendMessage(groupId, senderId, content, messageType = 1) { try { const sql = ` INSERT INTO messages (group_id, sender_id, message_type, content, created_at) VALUES (?, ?, ?, ?, NOW()) `;
const result = await this.db.query(sql, [groupId, senderId, messageType, content]); const messageId = result.insertId;
const message = { messageId: messageId, groupId: groupId, senderId: senderId, messageType: messageType, content: content, createdAt: new Date() };
await this.updateGroupLatestMessage(groupId, message);
await this.invalidateGroupCaches(groupId);
return message;
} catch (error) { console.error('发送消息失败:', error); throw error; } }
async getMessageCountAfter(groupId, afterMessageId) { try { const cacheKey = `msg_count_after:${groupId}:${afterMessageId}`; let count = await this.cache.get(cacheKey);
if (count !== null) { return parseInt(count); }
const sql = ` SELECT COUNT(*) as count FROM messages WHERE group_id = ? AND message_id > ? `;
const result = await this.db.query(sql, [groupId, afterMessageId]); count = result[0].count;
await this.cache.set(cacheKey, count, 300);
return count;
} catch (error) { console.error('获取消息数量失败:', error); return 0; } }
async getMessagesAfter(groupId, afterMessageId, limit = 100) { try { const sql = ` SELECT message_id, sender_id, message_type, content, created_at FROM messages WHERE group_id = ? AND message_id > ? ORDER BY message_id ASC LIMIT ? `;
const messages = await this.db.query(sql, [groupId, afterMessageId, limit]);
return messages;
} catch (error) { console.error('获取消息列表失败:', error); return []; } }
async getLatestMessage(groupId) { try { const cacheKey = `latest_msg:${groupId}`; let message = await this.cache.get(cacheKey);
if (message) { return message; }
const sql = ` SELECT message_id, sender_id, message_type, content, created_at FROM messages WHERE group_id = ? ORDER BY message_id DESC LIMIT 1 `;
const result = await this.db.query(sql, [groupId]);
if (result.length > 0) { message = result[0];
await this.cache.set(cacheKey, message, 3600);
return message; }
return null;
} catch (error) { console.error('获取最新消息失败:', error); return null; } }
async getRecentMessages(groupId, limit = 50) { try { const sql = ` SELECT message_id, sender_id, message_type, content, created_at FROM messages WHERE group_id = ? ORDER BY message_id DESC LIMIT ? `;
const messages = await this.db.query(sql, [groupId, limit]);
return messages.reverse();
} catch (error) { console.error('获取最近消息失败:', error); return []; } }
async getUserGroups(userId) { try { const cacheKey = `user_groups:${userId}`; let groups = await this.cache.get(cacheKey);
if (groups) { return groups; }
const sql = ` SELECT gm.group_id, g.group_name, g.avatar_url, gm.joined_at FROM group_members gm LEFT JOIN groups g ON gm.group_id = g.group_id WHERE gm.user_id = ? AND gm.is_active = 1 ORDER BY gm.joined_at DESC `;
groups = await this.db.query(sql, [userId]);
await this.cache.set(cacheKey, groups, 3600);
return groups;
} catch (error) { console.error('获取用户群聊列表失败:', error); return []; } }
async updateGroupLatestMessage(groupId, message) { try { const cacheKey = `latest_msg:${groupId}`; await this.cache.set(cacheKey, message, 3600); } catch (error) { console.error('更新群组最新消息缓存失败:', error); } }
async invalidateGroupCaches(groupId) { try { const pattern = `msg_count_after:${groupId}:*`; await this.cache.deletePattern(pattern);
} catch (error) { console.error('清理群组缓存失败:', error); } }
async getBatchLatestMessages(groupIds) { try { if (groupIds.length === 0) return {};
const cacheKeys = groupIds.map(groupId => `latest_msg:${groupId}`); const cachedMessages = await this.cache.mget(cacheKeys);
const messages = {}; const missedGroupIds = [];
groupIds.forEach((groupId, index) => { if (cachedMessages[index] !== null) { messages[groupId] = cachedMessages[index]; } else { missedGroupIds.push(groupId); } });
if (missedGroupIds.length > 0) { const placeholders = missedGroupIds.map(() => '?').join(','); const sql = ` SELECT m1.group_id, m1.message_id, m1.sender_id, m1.message_type, m1.content, m1.created_at FROM messages m1 INNER JOIN ( SELECT group_id, MAX(message_id) as max_message_id FROM messages WHERE group_id IN (${placeholders}) GROUP BY group_id ) m2 ON m1.group_id = m2.group_id AND m1.message_id = m2.max_message_id `;
const results = await this.db.query(sql, missedGroupIds);
const cacheUpdates = []; results.forEach(row => { messages[row.group_id] = row; cacheUpdates.push([`latest_msg:${row.group_id}`, row]); });
if (cacheUpdates.length > 0) { await this.cache.mset(cacheUpdates, 3600); } }
return messages;
} catch (error) { console.error('批量获取最新消息失败:', error); return {}; } } }
|