| 您的当前位置:首页 --> MYSQL教程 --> MySQL分表自增ID问题的解决方法 |
| MYSQL教程 MySQL分表自增ID问题的解决方法 |
| 浏览次数:1110 关键词 ( ) |
| 查看使用该CPU的产品 查看CPU天梯 |
| CPU型号:MySQL分表自增ID问题的解决方法 |
| 主频:Ghz |
| 睿频:Ghz |
| 核心数:个 |
| 不支持超核心 |
| 制作工艺: |
| 插槽类型: |
| 功耗:0W |
| L3缓存:0MB |
| 支持最大内存: 0GB |
| CPU详细参数 |
|
当我们对MySQL进行分表操作后,将不能依赖MySQL的自动增量来产生唯一ID了,因为数据已经分散到多个表中。 1. 通过MySQL表生成ID CREATE TABLE `ttlsa_com`.`create_id` ( `id` BIGINT( 20 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ) ENGINE = MYISAM 也就是说,当我们需要插入数据的时候,必须由这个表来产生id值,我的php代码的方法如下:
<?php
function get_AI_ID() {
$sql = "insert into create_id (id) values('')";
$this->db->query($sql);
return $this->db->insertID();
}
?>
这种方法效果很好,但是在高并发情况下,MySQL的AUTO_INCREMENT将导致整个数据库慢。如果存在自增字段,MySQL会维护一个自增 锁,innodb会在内存里保存一个计数器来记录auto_increment值,当插入一个新行数据时,就会用一个表锁来锁住这个计数器,直到插入结 束。如果是一行一行的插入是没有问题的,但是在高并发情况下,那就悲催了,表锁会引起SQL阻塞,极大的影响性能,还可能会达到 max_connections值。 2. 通过redis生成ID
function get_next_autoincrement_waitlock($timeout = 60){
$count = $timeout > 0 ? $timeout : 60;
while($r->get("serial:lock")){
$count++;
sleep(1);
if ($count > 10)
return false;
}
return true;
}
function get_next_autoincrement($timeout = 60){
// first check if we are locked...
if (get_next_autoincrement_waitlock($timeout) == false)
return 0;
$id = $r->incr("serial");
if ( $id > 1 )
return $id;
// if ID == 1, we assume we do not have "serial" key...
// first we need to get lock.
if ($r->setnx("serial:lock"), 1){
$r->expire("serial:lock", 60 * 5);
// get max(id) from database.
$id = select_db_query("select max(id) from user_posts");
// or alternatively:
// select id from user_posts order by id desc limit 1
// increase it
$id++;
// update Redis key
$r->set("serial", $id);
// release the lock
$r->del("serial:lock");
return $id;
}
// can not get lock.
return 0;
}
$r = new Redis();
$r->connect("127.0.0.1", "6379");
$id = get_next_autoincrement();
if ($id){
$sql = "insert into user_posts(id,user,message)values($id,'$user','$message')"
$data = exec_db_query($sql);
}
3. 队列方式
<?php
class common {
private $r;
function construct() {
$this->__construct();
}
public function __construct(){
$this->r=new Redis();
$this->r->connect('127.0.0.1', 6379);
}
function set_queue_id($ids){
if(is_array($ids) && isset($ids)){
foreach ($ids as $id){
$this->r->LPUSH('next_autoincrement',$id);
}
}
}
function get_next_autoincrement(){
return $this->r->LPOP('next_autoincrement');
}
}
$createid=array();
while(count($createid)<20){
$num=rand(1000,4000);
if(!in_array($num,$createid))
$createid[]=$num;
}
$id=new common();
$id->set_queue_id($createid);
var_dump($id->get_next_autoincrement());
监控队列数量,并自动补充队列和取到id但并没有使用 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持80vps。 |
| 下一个产品 SQL计算timestamp的差值的方法 上一个产品 MySQL ERROR 1045 (28000) 错误的解决办法 |