对 uuid 进行模运算以确定 shard_id

use*_*343 6 database postgresql math uuid sharding

我们有 Postgresql 数据库,我们正在那里做一些分片。我们也在做 READ 负载平衡。为此,首先我们检查位于哪个分片数据上。

我们根据这个公式得到分片 ID:

entry_id % num_of_shards = shard_id
Run Code Online (Sandbox Code Playgroud)

它运作良好。目前我们有自动递增 ids (int)。

我们想切换到 uuid v4。在 uuid 的情况下确定 shard_id 的公式是什么?

谢谢

Clo*_*eto 6

最简单的就是把 shard_id 变成一个文本值。如果您想要 16 个分片,则仅使用 uuid 中的第一个字符。对于 256 个分片,使用前 2 个字符,依此类推。

select substring(uuid_generate_v4()::text from 1 for 2) as shard_id;
 shard_id 
----------
 c6
Run Code Online (Sandbox Code Playgroud)

对于只有两个分片,获取第一个字符的最低有效位:

select
    substring(
        ('x' || substring(uuid_generate_v4()::text from 1 for 1))::bit(4) 
        from 4 for 1
    ) as shard_id
;
 shard_id 
----------
 0
Run Code Online (Sandbox Code Playgroud)

对于四个分片,获得 2 位 ( from 3 for 2),依此类推。或者对于一个整数作为评论:

select 
    (
        'x' || substring(uuid_generate_v4()::text from 1 for 1)
    )::bit(4)::int % 2 as shard_id
Run Code Online (Sandbox Code Playgroud)


Thi*_*ter 0

您使用 UUID 是否只是为了避免向用户显示连续的 ID?在这种情况下,保留序列式 ID 并添加 UUID(只需在其上添加一个 UNIQUE 索引)。这样您就可以继续使用模块,并且还可以在外键上使用简单的数字 ID。

如果您使用 UUID 是因为需要全局唯一 ID(因为序列始终是“本地”),则必须使用某种方法将 UUID 转换为数字。

最简单的方法可能是获取 UUID 的几位数字并将它们转换为数字。