全局唯一id生成器----UidGenerator

UidGenerator :

UidGenerator 由百度开发,是Java实现的, 基于 Snowflake算法的唯一ID生成器。UidGenerator以组件形式工作在应用项目中, 支持自定义workerId位数和初始化策略, 从而适用于 docker等虚拟化环境下实例自动重启、漂移等场景。

需要自己根源源码达成jar包,源码地址:https://github.com/baidu/uid-generator

引入依赖:



        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        

        
        
            mysql
            mysql-connector-java
            runtime
            8.0.12
        

        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.9
        

        
        
            cn.codesheep
            uid-generator
            1.0
        

    

application.properties中添加配置:

server.port=9999

spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

数据库新建一张表:

DROP TABLE IF EXISTS WORKER_NODE;
CREATE TABLE WORKER_NODE
(
ID BIGINT NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
HOST_NAME VARCHAR(64) NOT NULL COMMENT 'host name',
PORT VARCHAR(64) NOT NULL COMMENT 'port',
TYPE INT NOT NULL COMMENT 'node type: ACTUAL or CONTAINER',
LAUNCH_DATE DATE NOT NULL COMMENT 'launch date',
MODIFIED TIMESTAMP NOT NULL COMMENT 'modified time',
CREATED TIMESTAMP NOT NULL COMMENT 'created time',
PRIMARY KEY(ID)
)
 COMMENT='DB WorkerID Assigner for UID Generator',ENGINE = INNODB;

引入 UidGenerator源码中的 cached-uid-spring.xml文件,里面都是默认配置,不用做任何修改:




	
	

	
		

		
		 
		
		 
		
		
		
		
		 
		
		
		
		 
		
		
		
		 
		
		
		
		 
		
	


 或者使用默认的配置 default-uid-spring.xml :



    

    
    
    
    
    

 

引入 UidGenerator源码中关于工作节点(Worker Node)操作的 mapper xml 文件:WORKER_NODE.xml




	
		
		
		
		
		
		
		
	

	
		INSERT INTO WORKER_NODE
		(HOST_NAME,
		PORT,
		TYPE,
		LAUNCH_DATE,
		MODIFIED,
		CREATED)
		VALUES (
		#{hostName},
		#{port},
		#{type},
		#{launchDate},
		NOW(),
		NOW())
	

	

新建 UidConfig类,引入上文的 cached-uid-spring.xml:

@Configuration
@ImportResource(locations = { "classpath:uid/cached-uid-spring.xml" })
public class UidConfig {
}

新建 UidGenService,引入 UidGenerator 生成 UID的业务接口:

@Service
public class UidGenService {

    @Resource
    private UidGenerator uidGenerator;

    public long getUid() {
        return uidGenerator.getUID();
    }
}

新建 UidTestController,目的是方便我们用浏览器测试接口并观察效果:

@RestController
public class UidTestController {

    @Autowired
    private UidGenService uidGenService;

    @GetMapping("/testuid")
    public String test() {
        return String.valueOf( uidGenService.getUid() );
    }
}

 

你可能感兴趣的:(高并发与分布式)