在 确定分布策略 中,
我们讨论了在多租户用例中使用 Citus 所需的与框架无关的数据库更改。
当前部分研究如何构建与 Citus 存储后端一起使用的多租户 ASP.NET 应用程序。
示例应用
为了使这个迁移部分具体化,
让我们考虑一个简化版本的 StackExchange。
供参考,最终结果存在于 Github 上。
Schema
我们将从两张表开始:
CREATE TABLE tenants (
id uuid NOT NULL,
domain text NOT NULL,
name text NOT NULL,
description text NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE TABLE questions (
id uuid NOT NULL,
tenant_id uuid NOT NULL,
title text NOT NULL,
votes int NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
ALTER TABLE tenants ADD PRIMARY KEY (id);
ALTER TABLE questions ADD PRIMARY KEY (id, tenant_id);
我们 demo 应用程序的每个租户都将通过不同的域名进行连接。
ASP.NET Core 将检查传入请求并在 tenants
表中查找域。
您还可以按子域(或您想要的任何其他 scheme)查找租户。
注意 tenant_id
是如何存储在 questions
表中的。
这将使 :ref:colocate <colocation>
数据成为可能。
创建表后,使用 create_distributed table
告诉 Citus 对租户 ID 进行分片:
SELECT create_distributed_table('tenants', 'id');
SELECT create_distributed_table('questions', 'tenant_id');
接下来包括一些测试数据。
INSERT INTO tenants VALUES (
'c620f7ec-6b49-41e0-9913-08cfe81199af',
'bufferoverflow.local',
'Buffer Overflow',
'Ask anything code-related!',
now(),
now());
INSERT INTO tenants VALUES (
'b8a83a82-bb41-4bb3-bfaa-e923faab2ca4',
'dboverflow.local',
'Database Questions',
'Figure out why your connection string is broken.',
now(),
now());
INSERT INTO questions VALUES (
'347b7041-b421-4dc9-9e10-c64b8847fedf',
'c620f7ec-6b49-41e0-9913-08cfe81199af',
'How do you build apps in ASP.NET Core?',
1,
now(),
now());
INSERT INTO questions VALUES (
'a47ffcd2-635a-496e-8c65-c1cab53702a7',
'b8a83a82-bb41-4bb3-bfaa-e923faab2ca4',
'Using postgresql for multitenant data?',
2,
now(),
now());
这样就完成了数据库结构和示例数据。 我们现在可以继续设置 ASP.NET Core。
ASP.NET Core 项目
如果您没有安装 ASP.NET Core,请安装