uid-generator
Official website integration document: github.com/baidu/uid-g…
Since the springboot integration version is not available and the required steps are not available online, I will go through the detailed steps for uid-generator integration with springboot2
Uid-generator integrates initialization with springboot2
Create a MySQL database named baiduUidGenerator
Execute the following SQL
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;
Copy the code
Uid-generator is integrated with springboot2
Initialize a Springboot project and modify the POM file as follows
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.0 < / version > < / dependency > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! --for Mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < scope > runtime < / scope > < version > 8.0.12 < / version > < / dependency > <! -- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> The < version > 1.1.9 < / version > < / dependency > <! <dependency> <groupId>com.baidu. FSG </groupId> <artifactId> uID-generator </artifactId> < version > 1.0.0 - the SNAPSHOT < / version > < / dependency > < / dependencies >Copy the code
SQL > alter table application.properties;
server.port=9999 spring.datasource.url=jdbc:mysql://*.*.*.*:3306/baiduUidGenerator? useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=* spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis.mapper-locations=classpath:mapper/*.xml mybatis.configuration.map-underscore-to-camel-case=trueCopy the code
Create a UidGenService with the following content
package org.zxp.uidgeneratortest; import com.baidu.fsg.uid.UidGenerator; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * @program: uidgeneratortest * @description: * @author: X-Pacific zhang * @create: 2019-10-13 17:28 **/ @Service public class UidGenService { @Resource private UidGenerator uidGenerator; public long getUid() { return uidGenerator.getUID(); }}Copy the code
Create a WorkerNodeMapper with the same directory as the boot class. The following two steps are to solve the problem of UidGenerator integration with SpringBoot.
/* * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zxp.uidgeneratortest; import com.baidu.fsg.uid.worker.entity.WorkerNodeEntity; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; /** * DAO for M_WORKER_NODE * * @author yutianbao */ @Repository public interface WorkerNodeMapper { /** * Get {@link WorkerNodeEntity} by node host * * @param host * @param port * @return */ WorkerNodeEntity getWorkerNodeByHostPort(@Param("host") String host, @Param("port") String port); /** * Add {@link WorkerNodeEntity} * * @param workerNodeEntity */ void addWorkerNode(WorkerNodeEntity workerNodeEntity); }Copy the code
And start new DisposableWorkerIdAssigner directory content at the same level as follows
/*
* Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zxp.uidgeneratortest;
import com.baidu.fsg.uid.utils.DockerUtils;
import com.baidu.fsg.uid.utils.NetUtils;
import com.baidu.fsg.uid.worker.WorkerIdAssigner;
import com.baidu.fsg.uid.worker.WorkerNodeType;
import com.baidu.fsg.uid.worker.entity.WorkerNodeEntity;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* Represents an implementation of {@link WorkerIdAssigner},
* the worker id will be discarded after assigned to the UidGenerator
*
* @author yutianbao
*/
public class DisposableWorkerIdAssigner implements WorkerIdAssigner {
private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class);
@Autowired
private WorkerNodeMapper workerNodeMapper;
/**
* Assign worker id base on database.<p>
* If there is host name & port in the environment, we considered that the node runs in Docker container<br>
* Otherwise, the node runs on an actual machine.
*
* @return assigned worker id
*/
@Override
@Transactional
public long assignWorkerId() {
// build worker node entity
WorkerNodeEntity workerNodeEntity = buildWorkerNode();
// add worker node for new (ignore the same IP + PORT)
workerNodeMapper.addWorkerNode(workerNodeEntity);
LOGGER.info("Add worker node:" + workerNodeEntity);
return workerNodeEntity.getId();
}
/**
* Build worker node entity by IP and PORT
*/
private WorkerNodeEntity buildWorkerNode() {
WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
if (DockerUtils.isDocker()) {
workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
workerNodeEntity.setHostName(DockerUtils.getDockerHost());
workerNodeEntity.setPort(DockerUtils.getDockerPort());
} else {
workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
workerNodeEntity.setHostName(NetUtils.getLocalAddress());
workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
}
return workerNodeEntity;
}
}
Copy the code
Add annotations to the SpringBoot boot class, org.zxP. uidGeneratorTest needs to be updated to your project path
@RestController
@ComponentScan(basePackages = {"org.zxp.uidgeneratortest","com.baidu.fsg"})
@MapperScan("org.zxp.uidgeneratortest")
Copy the code
Create the mapper directory under resources and create the workerNodemapper. XML file as follows:
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="org.zxp.uidgeneratortest.WorkerNodeMapper"> <resultMap id="workerNodeRes" type="com.baidu.fsg.uid.worker.entity.WorkerNodeEntity"> <id column="ID" jdbcType="BIGINT" property="id"/> <result column="HOST_NAME" jdbcType="VARCHAR" property="hostName"/> <result column="PORT" jdbcType="VARCHAR" property="port"/> <result column="TYPE" jdbcType="INTEGER" property="type"/> <result column="LAUNCH_DATE" jdbcType="DATE" property="launchDate"/> <result column="MODIFIED" jdbcType="TIMESTAMP" property="modified"/> <result column="CREATED" jdbcType="TIMESTAMP" property="created"/> </resultMap> <insert id="addWorkerNode" useGeneratedKeys="true" keyProperty="id" parameterType="com.baidu.fsg.uid.worker.entity.WorkerNodeEntity"> INSERT INTO WORKER_NODE (HOST_NAME, PORT, TYPE, LAUNCH_DATE, MODIFIED, CREATED) VALUES ( #{hostName}, #{port}, #{type}, #{launchDate}, NOW(), NOW()) </insert> <select id="getWorkerNodeByHostPort" resultMap="workerNodeRes"> SELECT ID, HOST_NAME, PORT, TYPE, LAUNCH_DATE, MODIFIED, CREATED FROM WORKER_NODE WHERE HOST_NAME = #{host} AND PORT = #{port} </select> </mapper>Copy the code
The SpringBoot boot class adds the following methods (do some configuration instead of XML and test controller)
@Autowired
private UidGenService uidGenService;
@GetMapping("/getuid")
public String getUid() {
return String.valueOf( uidGenService.getUid() );
}
@Bean("disposableWorkerIdAssigner")
public DisposableWorkerIdAssigner disposableWorkerIdAssigner(){
DisposableWorkerIdAssigner disposableWorkerIdAssigner = new DisposableWorkerIdAssigner();
return disposableWorkerIdAssigner;
}
@Bean("cachedUidGenerator")
public UidGenerator uidGenerator(DisposableWorkerIdAssigner disposableWorkerIdAssigner){
CachedUidGenerator cachedUidGenerator = new CachedUidGenerator();
cachedUidGenerator.setWorkerIdAssigner(disposableWorkerIdAssigner);
return cachedUidGenerator;
}
Copy the code
test
Start springboot engineering visit: http://localhost:9999/getuid
Returns: 3686802606946000922
Success!