Several Methods for the game server to generate globally unique IDs and global methods

Source: Internet
Author: User

Several Methods for the game server to generate globally unique IDs and global methods

During server system development, we often need to store data asynchronously to adapt to high-concurrency requests, especially in distributed systems, at this time, you cannot wait for the database to be inserted to return an automatic id. Instead, you need to generate a globally unique id before inserting the database, using the Globally Unique id, in the game server, globally Unique IDS can be used for combination convenience in the future without key conflicts. You can also implement database/table sharding when your business grows in the future. For example, if a user's item needs to be placed in the same Shard, this fragment may be determined based on the user ID range value. For example, if the user ID is greater than 1000 and less than 100000, the user is in a shard. Currently, the following are commonly used:

1. Java UUID.

UUID. randomUUID (). toString () can be generated locally through the service program. ID generation does not depend on the database implementation.

Advantages:

ID generated locally, no remote call is required.

Globally Unique.

The horizontal scaling capability is very good.

 

Disadvantages:

The ID has 128 bits, which occupies a large amount of space and needs to be saved as a string type, resulting in extremely low indexing efficiency.

The generated ID does not contain Timestamp, which cannot guarantee increasing trend and is not highly dependent on database/table sharding.

 

2. Redis-based incr Method

Redis itself operates on a single thread, while incr ensures an atomic increment operation. Incremental step size can also be set.

Advantages:

Easy to deploy and use. You only need to call an apsaradb for redis api.

Multiple servers can share a redis service to reduce the development time of shared data.

Redis can be deployed in clusters to solve single point of failure (spof) problems.

Disadvantages:

If the system is too large, multiple n services will request redis at the same time, resulting in performance bottlenecks.

3. Solutions from Flicker

This solution is based on the database auto-increment id. It uses a separate database to generate IDS. For details, you can search for it online. I personally think it is very troublesome to use it, but it is not recommended.

 

4. Twitter Snowflake

Snowflake is an open-source distributed ID Generation Algorithm of twitter. Its core idea is to generate a long-type ID, with 41bit as the number of milliseconds, 10bit as the machine number, and 12bit as the serial number within milliseconds. In theory, a single machine can generate a maximum of 1000*(2 ^ 12) IDs per second, that is, approximately million IDs, which can fully meet the business needs.

 

Based on the idea of the snowflake algorithm, we can generate our own globally unique ID based on our business scenarios. Because the length of the long type in Java is 64 bits, the ID we designed must be controlled at 64 bits.

Advantages: high performance, low latency, independent applications, and chronological order.

 

Disadvantage: independent development and deployment are required.

 

For example, the ID we designed contains the following information:

| 41 bits: Timestamp | 3 bits: region | 10 bits: Machine ID | 10 bits: Serial Number |

 

Java code that generates a unique ID:

/**

* Custom ID Generator

* ID generation rule: ID up to 64 bits

*

* | 41 bits: Timestamp (MS) | 3 bits: Region (Data Center) | 10 bits: Machine ID | 10 bits: Serial Number |

*/

Public class GameUUID {

// Reference time

Private long twepoch = 1288834974657L; // Thu, 04 Nov 2010 01:42:54 GMT

// Number of bits in the region

Private final static long regionIdBits = 3L;

// Number of machine Identification Digits

Private final static long workerIdBits = 10L;

// Number of serial numbers

Private final static long sequenceBits = 10L;

 

// Maximum region flag ID

Private final static long maxRegionId =-1L ^ (-1L <regionIdBits );

// Maximum Machine ID

Private final static long maxWorkerId =-1L ^ (-1L <workerIdBits );

// Maximum Serial Number ID

Private final static long sequenceMask =-1L ^ (-1L <sequenceBits );

 

// Shift the machine ID left by 10 digits

Private final static long workerIdShift = sequenceBits;

// Shifts the Business ID by 20 digits to the left

Private final static long regionIdShift = sequenceBits + workerIdBits;

// The time is shifted to 23 digits in milliseconds

Private final static long timestampLeftShift = sequenceBits + workerIdBits + regionIdBits;

 

Private static long lastTimestamp =-1L;

 

Private long sequence = 0L;

Private final long workerId;

Private final long regionId;

 

Public GameUUID (long workerId, long regionId ){

 

// Throw an exception if it exceeds the specified range.

If (workerId> maxWorkerId | workerId <0 ){

Throw new IllegalArgumentException ("worker Id can't be greater than % d or less than 0 ");

}

If (regionId> maxRegionId | regionId <0 ){

Throw new IllegalArgumentException ("datacenter Id can't be greater than % d or less than 0 ");

}

 

This. workerId = workerId;

This. regionId = regionId;

}

 

Public GameUUID (long workerId ){

// Throw an exception if it exceeds the specified range.

If (workerId> maxWorkerId | workerId <0 ){

Throw new IllegalArgumentException ("worker Id can't be greater than % d or less than 0 ");

}

This. workerId = workerId;

This. regionId = 0;

}

 

Public long generate (){

Return this. nextId (false, 0 );

}

 

/**

* Actually generated code

*

* @ Param isPadding

* @ Param busId

* @ Return

*/

Private synchronized long nextId (boolean isPadding, long busId ){

 

Long timestamp = timeGen ();

Long paddingnum = regionId;

 

If (isPadding ){

Paddingnum = busId;

}

 

If (timestamp <lastTimestamp ){

Try {

Throw new Exception ("Clock moved backwards. Refusing to generate id for" + (lastTimestamp-timestamp) + "milliseconds ");

} Catch (Exception e ){

E. printStackTrace ();

}

}

 

// If the last generation time is the same as the current time

If (lastTimestamp = timestamp ){

// Auto-increment of sequence, because sequence only has 10 bits, so the sequenceMask and sequenceMask should be separated from the high position.

Sequence = (sequence + 1) & sequenceMask;

// Determine whether the event exists, that is, the value exceeds 1024 every millisecond. When the value is 1024, the sequence is equal to 0 in the phase with sequenceMask.

If (sequence = 0 ){

// The spin waits until the next millisecond.

Timestamp = tailNextMillis (lastTimestamp );

}

} Else {

// If different from the last generation time, reset the sequence, that is, starting from the next millisecond, and the sequence count is accumulated again from 0,

// To ensure that the tail is more random, set a random number for the last digit.

Sequence = new SecureRandom (). nextInt (10 );

}

 

LastTimestamp = timestamp;

 

Return (timestamp-twepoch) <timestampLeftShift) | (paddingnum <regionIdShift) | (workerId <workerIdShift) | sequence;

}

 

// Prevent the generated time from being smaller than the previous time (due to issues such as NTP callback) and maintain the incremental trend.

Private long tailNextMillis (final long lastTimestamp ){

Long timestamp = this. timeGen ();

While (timestamp <= lastTimestamp ){

Timestamp = this. timeGen ();

}

Return timestamp;

}

 

// Obtain the current Timestamp

Protected long timeGen (){

Return System. currentTimeMillis ();

}

}

 

Note the following when using a custom method:

In order to maintain the growth trend, it is necessary to avoid the earlier time of some servers, the later time of some servers, the time of all servers needs to be controlled, and the NTP time should be avoided; during the time span of milliseconds, the serial number is always set to 0, which leads to a large number of IDs with the serial number 0. As a result, the generated ID is not uniform after the modulo operation. Therefore, the serial number is not set to 0 every time, instead, return a random number ranging from 0 to 9. (This code reference: http://www.jianshu.com/p/61817cf48cc3)

 

We can select these methods as needed. In game server development, you can choose your own game type, such as mobile games. You can use a simple redis method, which is simple and error-prone, because the number of concurrent new IDs for a single game server is not large, it can fully meet the needs. For a large world game server, it is mainly distributed, so we can use the snowflake method. The above snowflake code is just an example and needs to be customized according to our own needs, therefore, there is an additional amount of development, and pay attention to the precautions mentioned above. Reference: http://www.youxijishu.com/h-nd-147-2_323.html

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.