gpt4 book ai didi

django - 使用 Django 简化分片

转载 作者:行者123 更新时间:2023-11-29 11:09:16 24 4
gpt4 key购买 nike

我有一个 Django基于多个项目 PostgreSQL服务器。

我希望用户是 sharded在这些数据库服务器上使用相同的 sharding logic used by Instagram :

用户ID => 逻辑分片ID => 物理分片ID => 数据库服务器=> 模式=> 用户表

  • 逻辑分片 ID 直接根据用户 ID 计算得出(用户 ID 中嵌入了 13 位)。
  • 从逻辑到物理分片 ID 的映射是硬编码的(在某些配置文件或静态表中)。
  • 从物理分片 ID 到数据库服务器的映射也是硬编码的。 Instagram 使用 Pgbouncer此时检索到适当数据库服务器的池化数据库连接。
  • 每个逻辑分片都存在于自己的 PostgreSQL schema 中(对于那些不熟悉 PostgreSQL 的人来说,这不是一个表模式,它更像是一个命名空间,类似于 MySQL 'databases' )。该架构的名称很简单,类似于“shardNNNN”,其中 NNNN 是逻辑分片 ID。
  • 最后,查询适当架构中的用户表。

如何在 Django 中尽可能简单地实现这一点?

理想情况下,我希望能够编写如下 Django 代码:

获取实例

# this gets the user object on the appropriate server, in the appropriate schema:
user = User.objects.get(pk = user_id)

获取相关对象

# this gets the user's posted articles, located in the same logical shard:
articles = user.articles

创建实例

# this selects a random logical shard and creates the user there:
user = User.create(name = "Arthur", title = "King")
# or:
user = User(name = "Arthur", title = "King")
user.save()

按名称搜索用户

# fetches all relevant users (kings) from all relevant logical shards
# - either by querying *all* database servers (not good)
# - or by querying a "name_to_user" table then querying just the
# relevant database servers.
users = User.objects.filter(title = "King")

为了让事情变得更复杂,我使用 Streaming Replication将每个数据库服务器的数据复制到多个从服务器。 master 应该用于写入,slave 应该用于读取。

Django 提供对 automatic database routing 的支持这对于上面的大部分可能已经足够了,但是我坚持使用 User.objects.get(pk = user_id) 因为路由器无法访问查询参数,所以它不知道用户 ID 是什么,它只知道代码正在尝试读取用户模型。

我很清楚分片应该只作为最后的优化手段使用,因为它有局限性并且确实使事情变得非常复杂。大多数人不需要分片:优化的主/从架构可以走很长的路。但让我们假设我确实需要分片。

简而言之:如何尽可能简单地在 Django 中分片数据?

非常感谢您的帮助。

注意

有一个existing question这非常相似,但恕我直言,它太笼统了,缺乏精确的例子。我想将范围缩小到我感兴趣的特定分片技术(Instagram 方式)。

最佳答案

Mike Clarke 最近在 PyPgDay 上发表了关于 Disqus 如何将他们的用户与 Django 和 PostgreSQL 分片的演讲。他写了a blog post关于他们是如何做到的。

Several strategies can be employed when sharding Postgres databases. At Disqus, we chose to shard based on table name. Where as the original table name as generated by Django might be comments_post, our sharding tools will rewrite the SQL to query a table comments_post_X, where X is the shard ID calculated based on a consistent hashing scheme. All these tables live in a single schema, on a single database instance.

此外,他们还发布了 some code as part of a sample application演示它们如何分片。

关于django - 使用 Django 简化分片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11782274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com