date: 2017-01-03 13:14
唯一ID引發的血案
寫這篇 blog 原因是業務中遇到 生成唯一ID的場景 卻沒有按照需求生成唯一ID,由此引發了一番 亂燉,業務中目前使用的方案:
// mysql 自增ID + 事務 + 時間 + 隨機數
public function generateTradeNumber()
{
$tradeTime = date('YmdHi', time());
$lastTrade = TradeNumber::findBySql('SELECT * FROM `Trade` ORDER BY id DESC LIMIT 1 FOR UPDATE');
$lastTradeTime = '';
if (!empty($lastTrade)) {
$lastTradeNumber = $lastTrade->getTradeNumber();
$lastTradeTime = substr($lastTradeNumber, 0, 12);
$lastTradeSerial = substr($lastTradeNumber, 12);
if ($tradeTime == $lastTradeTime) {
return $lastTradeTime . ($lastTradeSerial >= 99999 ? $lastTradeSerial + 1 : '0' . ($lastTradeSerial + 1));
}
}
$initSerialNumber = rand(10000, 99999);
return $tradeTime . '0' . $initSerialNumber;
}
簡單解釋一下:
- 唯一 TradeNumber 由 2 部分組成:當前時間 12 位 + 6 位數字
- 時間粒度到 分:
date('YmdHi', time())
- 每次生成時,先鎖死最后一條 Trade,當前分鐘第一個進來的 Trade 會分配
rand(10000, 99999)
(這樣做是為了保持長度一致,以及防止被人找出規律來),之后的 Trade 在此基礎上 +1
然而實際上并沒有達到 唯一ID 的目的,查詢數據庫發現還是有重復 TradeNumber 存在
php uniqid() 分析
php manual uniqid()
詳細的分析當然是直接看源碼最清楚了,不過 php manual 已經說了:based on the current time in microseconds
。并且 php manual 中已經詳細說明了這個問題,詳細可以查看 php manual note 中的內容,note 中提供了另外一種方案:
function uniqidReal($lenght = 13) {
// uniqid gives 13 chars, but you could adjust it to your needs.
if (function_exists("random_bytes")) {
$bytes = random_bytes(ceil($lenght / 2));
} elseif (function_exists("openssl_random_pseudo_bytes")) {
$bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
} else {
throw new Exception("no cryptographically secure random function available");
}
return substr(bin2hex($bytes), 0, $lenght);
}
這種方案的原理:隨機數
。當然這個隨機數概率就比 rand(10000, 99999)
小多了,畢竟加入了英文字母。那么,回到我們的主題,隨機數 === 唯一ID
?顯然,無論概率怎么小,還是存在重復的可能(-_-)。
唯一ID原理
Linux多線程與同步:http://www.cnblogs.com/vamei/archive/2012/10/09/2715393.html
《高性能linux服務器編程》- 高性能 io - 進程相關部分
唯一ID生成原理與PHP實現:http://mp.weixin.qq.com/s/bagOgzdwLyZv_ITNVnYfoQ / https://github.com/liexusong/atom
其實非常的簡單,只要保證從同一個地方產生,并按照不重復的規律生成。聯想一下 mysql 的自增ID,就是 同一張表,依次遞增。所以,自增ID真正的難點:同一個地方生成。但是,在多進程、多線程的場景下,這個 地方 就會成為 競態資源
。要了解race condition, mutex和condition variable的概念,請參考上面的博文 -- Linux多線程與同步。
多線程同步方式:
- 互斥鎖(mutex):一個線程申請了互斥鎖,然后進行 原子操作,其他進程必須要等待此線程釋放互斥鎖,才能成功申請。
- 條件變量(condition variable):配合互斥鎖一起使用,在 多個線程等待某個條件發生 時的場景下使用
- 讀寫鎖(reader-writer lock):和互斥鎖類似,鎖有 3 種狀態 -- R、W、unlock。如果資源上 R 鎖,其他線程可以繼續申請 R 鎖;如果需要申請 W 鎖,必須等待其他進程都釋放 R 鎖;如果資源上 W 鎖,其他線程必須等待其釋放
多進程的同步方式:
- 管道
- 共享內存
是不是有點峰回路轉,怎么突然跑到操作系統層面了?whatever,你曾經學的操作系統原理,就是這么有用。
再來簡單的剖析一下 唯一ID生成原理與PHP實現 這篇博文中提到的 snowflake算法:
- 唯一ID組成:64bit, 1bit(不用)+ 41bit(時間戳)+ 10bit(機器id)+ 12bit(序列號)
- 時間毫秒級(可以用2082年),每毫秒最多
2^12=4096
個請求,如果超過了,就分配到下一毫秒 - 為什么分機器ID:達到分布式計算,避免不同機器間同步帶來的性能損耗
代碼就不貼了,大家自己看,挺簡單的。
唯一ID的php實現
韓天峰(Rango) - 從零開始編寫第一個PHP擴展:http://wiki.swoole.com/wiki/page/238.html
淘寶信海龍 php 擴展開發:http://www.bo56.com/category/programming-language/php-programming-language
唯一ID生成原理與PHP實現:http://mp.weixin.qq.com/s/bagOgzdwLyZv_ITNVnYfoQ / https://github.com/liexusong/atom
韓天峰(Rango) Yii/Yaf/Swoole3個框架的壓測性能對比:http://rango.swoole.com/archives/254
由于 php-fpm 是基于進程管理,每個pfm子進程都是相互獨立的,想要實現 同一個地方生成,就需要依靠擴展。而php擴展開發,不少業內大牛都貼了教程,無恥引用幾個。
推薦學習次序:
- 韓天峰(Rango) - 從零開始編寫第一個PHP擴展
- 淘寶信海龍 php 擴展開發系列教程
- 查看
https://github.com/liexusong/atom
源碼:github 上的文檔只提到了 2 個函數,還是直接讀源碼吧,主要是atom.c
測試:
- cli 下的測試
// php test
for ($i=0; $i < 20; $i++) {
$id = atom_next_id(); // different
$info = atom_explain($id); // the same
echo $id . "\t" . date('YmdHis', $info['timestamp']) . "\t" . $info['datacenter'] . "\t" . $info['worker'] . "\n";
}
// ext atom source code
retval = ((current - context->twepoch) << context->timestamp_left_shift)
| (context->datacenter_id << context->datacenter_id_shift)
| (context->worker_id << context->worker_id_shift)
| context->sequence;
寫在最后
《高性能mysql》
MOOC - 《linux操作系統原理與應用》
swoole官方教程和 rango 的博客
我的 docker 環境:https://coding.net/u/daydaygo/p/docker/git
《Just for Fun》linus 自傳
由于本身的技術局限,對 mysql 中 這套 SELECT FOR UPDATE
不太熟悉,這個點有待提高,推薦《高性能mysql》。
操作系統原理到底有沒有用?如果看到 進程、線程、共享內存、管道 等等名詞感覺不太熟悉(熟悉名詞和知道怎么用還隔著好遠呢),最好還是多了解一點。
- 推薦《linux操作系統原理與應用》:這個是大學教材,找個MOOC網看看在線視頻,網易公開課、中國大學MOOC、學堂在線 等等
- 《高性能linux服務器編程》:還有鼎鼎大名的《Unix Network Programing》,就是實在是太厚了
- swoole官方教程和 rango 的博客:c10k問題、時間循環、swoole/nginx/go/nodejs 實現原理對比、線程/進程/協程 對比 等等
當然,還有一個問題需要解決:說了這么半天,程序還是得要在 linux 下面跑,我的 windows 怎么辦,給自己打一下廣告,我的 docker 環境:https://coding.net/u/daydaygo/p/docker/git
最后的最后,寫在這個沒有出去浪的元旦假期:
- 且將新火試新茶,詩酒趁年華
- Just for Fun