http://lztian.com/blog/5921.html
借用MySQL 的 auto_increment 特性可以產(chǎn)生唯一的可靠ID。
表定義,關(guān)鍵在于auto_increment,和UNIQUE KEY的設(shè)置:
1 2 3 4 5 6 | CREATE TABLE `Tickets64` ( `id` bigint (20) unsigned NOT NULL auto_increment, `stub` char (1) NOT NULL default '' , PRIMARY KEY (`id`), UNIQUE KEY `stub` (`stub`) ) ENGINE=MyISAM |
需要使用時,巧用replace into語法來獲取值,結(jié)合表定義的UNIQUE KEY,確保了一條記錄就可以滿足ID生成器的需求:
1 2 | REPLACE INTO Tickets64 (stub) VALUES ( 'a' ); SELECT LAST_INSERT_ID(); |
以上方式中,通過MySQL的機(jī)制,可以確保此ID的唯一和自增,且適用于多并發(fā)的場景。官方對此的描述:https://dev.mysql.com/doc/refman/5.0/en/information-functions.html
1 2 3 | It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values. |
需要注意的是,若client采用PHP,則不能使用mysql_insert_id()獲取ID,原因見《mysql_insert_id() 在bigint型AI字段遇到的問題》:http://kaifage.com/notes/99/mysql-insert-id-issue- with-bigint-ai-field.html。
Flickr 采取了此方案: http://code.flickr.net/2010/02/08/ticket-servers-distributed-unique-primary-keys-on-the-cheap/
相關(guān):
http://www.zhihu.com/question/30674667
http://my.oschina.net/u/142836/blog/174465