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. 队列方式其实这也算是上面的一个解说 使用队列服务,如redis、memcacheq等等,将一定量的ID预分配在一个队列里,每次插入操作,先从队列中获取一个ID,若插入失败的话,将该ID再次添加到队列中,同时监控队列数量,当小于阀值时,自动向队列中添加元素。这种方式可以有规划的对ID进行分配,还会带来经济效应,比如QQ号码,各种靓号,明码标价。如网站的userid, 允许uid登陆,推出各种靓号,明码标价,对于普通的ID打乱后再随机分配。 <?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"); }