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);
}
热点聚合:
©CopyRight 2010-2020 EASCK.COM Inc All Rights Reserved. 易采站长站 版权所有
微信扫一扫