mysql分库分表ID分配_MySQL分库分表的全局唯一ID生成器方案

借用MySQL 的 auto_increment 特性可以产生唯一的可靠ID。

表定义,关键在于auto_increment,和UNIQUE KEY的设置:

1

2

3

4

5

6CREATE TABLE `Tickets64` (

`id`bigint(20) unsignedNOT NULL auto_increment,

`stub`char(1)NOT NULL default '',

PRIMARY KEY  (`id`),

UNIQUE KEY `stub` (`stub`)

) ENGINE=MyISAM

需要使用时,巧用replace into语法来获取值,结合表定义的UNIQUE KEY,确保了一条记录就可以满足ID生成器的需求:

1

2REPLACE INTO Tickets64 (stub)VALUES ('a');

SELECT LAST_INSERT_ID();

以上方式中,通过MySQL的机制,可以确保此ID的唯一和自增,且适用于多并发的场景。官方对此的描述:https://dev.mysql.com/doc/refman/5.0/en/information-functions.html

1

2

3It 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/

相关:

http://www.zhihu.com/question/30674667

http://my.oschina.net/u/142836/blog/174465

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值