I love the java series --- [id solutions for distributed generation]

1. Distributed generation ID Solution

Why should generate a unique id:
because global commodity requires a unique id, if you use database auto-increment primary keys, then the database can ensure that a single database that id is unique,
but if the database cluster situation, can not guarantee that, globally unique id.

1.1 Distributed generation ID Solutions

1.1.1 UUID

Common way. You can use a database program can also be used to generate, in general globally unique.

advantage:

1) simple and convenient code.

2) generation ID performance is very good, basically there will be no performance problems.

3) the only global, met in data migration, data consolidation system, or database changes, etc., you can easily deal with.

 Disadvantages:

1) there is no sorting, no guarantee that trend increase.

2) UUID often use strings to store, query efficiency is relatively low.

3) storage space is relatively large, if it is a massive database, you need to consider storage issues.

4) large amount of data transmission

5) unreadable.

1.1.2 Redis generation ID

When the ID is generated when performance is not required to use the database, we can try to use Redis to produce ID. Depending mainly on the Redis is single-threaded, so it can be used to generate a globally unique ID. INCR atomic operation can be realized and INCRBY Redis.

advantage:

1) does not depend on a database, flexibility, and superior performance database.

2) natural ordering digital ID, the results need to sort tab or helpful.

Disadvantages:

1) If the system does not have the Redis, need to introduce new components, increasing system complexity.

2) require coding and configuration workload is relatively large.

3) transmission network caused performance degradation.

1.1.3 open source algorithm snowflake

 Twitter is distributed snowflake ID open generation algorithm, the result is a long type's ID. Its core idea is: Use as milliseconds ID 41bit, 10bit as the machine (5 bit data center, five-bit machine ID), 12bit (meaning that each node may be generated every millisecond as a serial number in ms 4096 ID), and finally there is a sign bit is always 0

1.2 snowflake Quick Start

1.2.1 Quick Start

(1)新建工程,将资料/工具类下的IdWorker.java拷贝到工程中。

(2)编写代码

     IdWorker idWorker=new IdWorker(1,1);
​
        for(int i=0;i<10000;i++){
            long id = idWorker.nextId();
            System.out.println(id);
        }

1.2.2 配置分布式ID生成器

(1)IdWorker.java拷贝到changgou_common工程com.highgou.util包中

(2)highgou_service_goods的application.yml添加配置

workerId: 0
datacenterId: 0

(3)修改GoodsApplication,增加代码

  @Value("${workerId}")
    private Integer workerId;
​
    @Value("${datacenterId}")
    private Integer datacenterId;
​
    @Bean
    public IdWorker idWorker(){
        return new IdWorker(workerId,datacenterId);
    }

(4)在任意Controller类中注入IdWorker,测试是否能够生成ID

 

Guess you like

Origin www.cnblogs.com/hujunwei/p/11894915.html