【问题标题】:Architecture of private chat私聊架构
【发布时间】:2016-03-31 11:05:16
【问题描述】:

我想做私人聊天服务。现在我有一个关系数据库(PostgreSQL)来存储我的消息和线程(线程 - 用户之间的私人房间)。

我有以下表格:

1) 消息:idtextdatetimesender_idthread_id, is_read

2) 主题:id

3) Thread_Participants:thread_iduser_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

但是这样的请求意味着相当困难和缓慢的请求......我怎样才能用快速的方式得到它?或者也许还有另一种消息的方式或架构?

【问题讨论】:

  • @Jakub Kania:不,我关于整个建筑的问题,我可以改变它。分组最大查询的优化是我的问题的一部分,或者只是解决方法之一。

标签: postgresql chat groupwise-maximum


【解决方案1】:
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;

【讨论】:

  • 对!例如通过触发器。但我害怕这种方式,因为每条消息我都需要更新两个表(消息和线程)而不是一个(消息)。我的意思是它会增加每条消息的数据库负载...还有另一种方法可以在 Redis 中存储新消息并将它们推送到由大量消息的一部分延迟(在后台)的关系数据库,例如 10 分钟一次...但我不知道...
  • @Anton:这是你必须做出的权衡:)
  • 我明白了 :) 有趣的是它是如何在 vkontakte 中实现的?
  • @Anton:很多自定义数据库。看看这个:habrahabr.ru/company/vkontakte/blog/214877
猜你喜欢
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 2017-04-13
  • 2016-03-19
  • 2015-07-22
  • 2016-07-14
  • 2011-08-13
  • 1970-01-01
相关资源
最近更新 更多