基于 Optimus Id 的数据库自增 id 隐藏方案
目前尝试过 snowflake, uuid, hashids 等形式的方案.
snowflake生成的 id 能满足需求, 但是有个问题是 id 长度太长, 给前端的时候需要转成 string, 如果把这个 string id 在MySQL 8下进行查询的时候, 会无法查询到(具体表现为一个为bigint且有索引的字段和另一个字段 Where 的时候, 在PHP PDO下以String类型查询在这个bigint无法查询到, 水平有限跟踪到PDO层面, 问题应该出在参数绑定上).uuid太长, 太丑hashids包含字母, 也觉得丑
今天在 hashids.org上偶然发现一个 optimus 的推荐, hashids 对它的介绍是:
If you need your ids to consist of only numbers, check out Optimus. It’s based on Knuth’s integer hash method and produces obfuscated integer ids (and does it faster too). There are PHP and G0 implementations.
好家伙, 这不就是我想要的吗.☺️
安装(需要 GMP 扩展支持)
composer require jenssegers/optimus
使用
php vendor/bin/optimus spark
Prime: 1527589457
Inverse: 1570528945
Random: 1457286732
Bit length: 31
new Optimus(1527589457, 1570528945, 1457286732, 31);
Laravel 中使用
// config/optimus.php
return [
'prime' => env('OPTIMUS_PRIME', 1831559361),
'inverse' => env('OPTIMUS_INVERSE', 1091482001),
'random' => env('OPTIMUS_RANDOM', 95201620),
'bit_length' => env('OPTIMUS_BIT_LENGTH', 31),
];
// app/Providers/OptimusIdServiceProvider.php
...
public function boot()
{
$this->app->singleton('OptimusId', fn () => new Optimus(
config('optimus.prime'),
config('optimus.inverse'),
config('optimus.random'),
config('optimus.bit_length')
));
}
...
//
app('OptimusId')->encode(1)
关于 LearnKu
推荐文章: