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.