Mysql Distributed Database ID generator solution

Source: Internet
Author: User

When you use a distributed database system, you will be faced with the problem of generating unique identifiers for records. The traditional single table is certainly solved by the built-in auto-increment primary key. However, we do not recommend this because there will be duplicate IDs in database splitting in the future.
Many people will first think of MongoDB ObjectId and UUID, but this string type will bring complexity to the program, not only the storage space is large, but also the sort cannot be well supported. The unique identifier of my current project must meet at least the following requirements:
Uniqueness
Sortable

Sequential increase (required for efficient B-Tree index storage)

Efficient, avoiding complex operations

Solution 1: Use the auto-increment mechanism of the database
Use a dedicated database to generate an ID:

Create table 'tacs '(
'Id' bigint (20) not null AUTO_INCREMENT,
'Stub' char (1) not null default 'A ',
Primary key ('id '),
Unique key 'job' ('job ')
) ENGINE = MyISAM default charset = utf8;
 
# Use the following statement to obtain a unique id
Replace into tickets (stub) VALUES ('A ');
SELECT LAST_INSERT_ID ();

Of course, to avoid SPOF, you can deploy multiple servers. For example, set the auto-increment step to 2 (auto-increment = 2 ), at the same time, set auto-increment-offset to 1, 2, so that the auto-increment id of the first database server is 1 3 5 7 9 and the second database server is 2 4 6 8 10. Note that the sequence table is the MyISAM engine and reads and writes the serial data.
Solution 2: Auto-increment by memory
The above write database solution has performance problems and latency when the concurrency is large, so auto-increment in the memory will speed up generation.

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.