Flickr是如何生成唯一ID的,GUID?一致性hash?都不是,使用Mysql的key自动递增即可。
Mysql中有一个非标准的扩展,语法为REPLACE INTO,虽然INERT ON DUPLICATE KEY UPDATE也具有相同的功能,但是REPLACE INTO仍然得到支持。
Flickr使用的就是REPLACE INTO来生成全局唯一的ID。
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
The Tickets64 schema looks like:
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 #这里创建了一个表,专门用来生成KEY的
SELECT * from Tickets64
returns a single row that looks something like:
+-------------------+------+
| id | stub |
+-------------------+------+
| 72157623227190423 | a |
+-------------------+------+
When I need a new globally unique 64-bit ID I issue the following SQL:
REPLACE INTO Tickets64 (stub) VALUES ('a');
SELECT LAST_INSERT_ID(); #每次需要获取key的时候,执行这个查询,就能获得不同的key,就是LAST_INSERT_ID()的返回值
然后他们使用了2个这样的服务器,让它们轮流产生key,并且每个server的auto-increment-increment和auto-increment-offset都是不同的。全局唯一key就这样诞生了,不过我还是有点怀疑是不是如作者所言那么给力。作者最后说这个玩意从2006年到现在work shcokingly well........有需要的时候,也试试它这个方法吧。原文链接:http://code.flickr.net/2010/02/08/ticket-servers-distributed-unique-primary-keys-on-the-cheap/