Several ways to generate global IDs after the MySQL database is divided into tables

Source: Internet
Author: User
Tags cas delete key redis mysql database


A recent project, due to the large number of data, needs to be data-table. The data is stored on Taobao's TDDL. The original ID cannot be used since the table is divided. TDDL is good for Java support, and does not need to consider the global ID problem after the table is divided. But this project uses PHP for development and must generate a global ID on its own. Here are a few of the table scenarios, just to be discussed.

Method 1: Use CAS (compare and swap)

In fact, this is not strictly a CAS, but using the idea of comparing the exchange of atomic operations.

Generate ideas as follows:

Each time a global ID is generated, the current global maximum ID is obtained from the sequence table. Then add a 1 operation on the obtained global ID. Update the value plus 1 to the database. Updates are critical.

If the value of 1 is 203, the table name is users, and the datasheet structure is as follows:

The code is as follows Copy Code
CREATE TABLE ' SEQUENCE ' (
' Name ' varchar not NULL COMMENT ' table name of table ',
' GID ' bigint not NULL COMMENT ' maximum global ID ',
PRIMARY KEY (' name ')
) Engine=innodb

So the UPDATE statement is.

The code is as follows Copy Code

Update sequence Set gid = 203 where name = ' users ' and GID < 203;

The and GID < 203 of the SQL statement is to ensure that the value of the GID is only increased in the concurrent environment.

If the effect of the UPDATE statement is 0, the other processes already generate 203 of this value earlier and write to the database. You will need to repeat the previous steps to generate the new.

The code implementation is as follows:

The code is as follows Copy Code
//$name table name
function next_id_db ($name) {
   //Get Database Global Sequence object
    $seq _dao = Wk_sequence_ Dao_sequence::getinstance ();
    $threshold = 100;//maximum number of attempts
    for ($i = 0; $i < $threshold; $i + +) {
  ;       $last _id = $seq _dao->get_seq_id ($name);//Get Global ID from database
         $id = $last _id +1;
        $ret = $seq _dao->set_seq_id ($name, $id);
        if ($ret) {
             return $id;
            break;
       }
   }
    return false;
}

Scenario 2: Use global locks.

The lock mechanism is generally used in concurrent programming. In fact, the generation of global IDs is also a solution to concurrency problems.

Generate ideas as follows:

When you use the Redis Setnx method and the Memcace Add method, False is returned if the specified key already exists. Using this feature, the global lock is implemented.

Detects whether a specified key exists each time before a global ID is generated.

If not, use the Redis incr method or Memcache increment to add 1 operations. The return value of these two methods is the value added after 1.

If present, the program enters the loop wait state. During the cycle, the key is continuously detected and if key does not exist, perform the above operation.

The code is as follows:

The code is as follows Copy Code
Using Redis to implement
$name as logical table name
function Next_id_redis ($name) {
$redis = Wk_redis_util::getredis ();//Get Redis Object
$seq _dao = Wk_sequence_dao_sequence::getinstance ();//get store Global ID datasheet Object
if (!is_object ($redis)) {
throw new Exception ("fail to create Redis object");
}
while (1) {
Detects whether a key exists, which is equivalent to detecting whether the lock exists
$ret = $redis->setnx ("sequence_{$name}_flag", Time ());
if ($ret) {
Break
}
$time = $redis->get ("sequence_{$name}_flag");
if (Time ()-$time > 1) {//If the loop wait is greater than 1 seconds, no longer wait.
Break
}
}
$id = $redis->incr ("sequence_{$name}");
If the operation fails, the global ID is obtained from the sequence table and loaded into the Redis
if (intval ($id) = = 1 or $id = = False) {
$last _id = $seq _dao->get_seq_id ($name);//Get global ID from database
if (!is_numeric ($last _id)) {
throw new Exception ("fail to get ID from DB");
}
$ret = $redis->set ("sequence_{$name}", $last _id);
if ($ret = = False) {
throw new Exception ("fail to set Redis key [sequence_{$name}]");
}
$id = $redis->incr ("sequence_{$name}");
if (!is_numeric ($id)) {
throw new Exception ("fail to incr redis key [sequence_{$name}]");
}
}
$seq _dao->set_seq_id ($name, $id);//writes the generated global ID to the datasheet sequence
$redis->delete ("sequence_{$name}_flag");//delete key, equivalent to release lock
$DB = null;
return $id;
}

Solution 3:redis and DB combined.

Using Redis to manipulate memory directly may be a better performance. But if Redis dies, how do you deal with it? Combine the above two schemes to provide better stability.

The code is as follows:

The code is as follows Copy Code
function next_id ($name) {
try{
return $this->next_id_redis ($name);
}
catch (Exception $e) {
return $this->next_id_db ($name);
}
}

In addition to the generation of global IDs, flicker and Twitter have announced their own solutions. Interested people, can understand the next

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.