我想做私有(private)聊天服务。现在我有一个关系数据库 (PostgreSQL) 用于存储我的消息和线程(线程 - 用户之间的私有(private)房间)。
我有下表:
1)消息:id、text、datetime、sender_id、thread_id, is_read
2) 主题:id
3) Thread_Participants: thread_id, user_id
Message表通过Thread_Participants表通过Many_to_Many关系与Thread相连。
在我的架构中,用户通过 WebSocets 和 Redis 数据库的 Pub/Sub 交换消息。
但我认为我需要将消息存储在关系数据库中,这样更安全。也许我错了。
但是我在获取用户线程的历史记录时遇到了问题。我想请求(关系数据库)以下字段:
thread_id,
last_message_in_this_thread,
count_of_messages_in_this_thread,
datetime_of_last_message_in_this_thread,
username_of_last_message_in_this_thread
但是这样的请求意味着非常艰难和缓慢的请求......我怎样才能用快速的方式得到它?或者可能有另一种消息传递方式或架构?
最佳答案
last_message_in_this_thread
count_of_messages_in_this_thread
datetime_of_last_message_in_this_thread
username_of_last_message_in_this_thread
所有这些都可以缓存在线程表中。此查询将非常快,因为您不必加入/查询消息或用户表。唯一的缺点是:对于每条新消息,您现在必须执行两次写入而不是一次。
INSERT INTO messages(...) values (...);
UPDATE threads SET datetime_of_last_message = now(), count_of_messages = count_of_messages + 1 where id = 123;
关于postgresql - 私聊架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34462335/