1. Basic Overview

1.SpringBoot integrates Baidu open source UidGenerator and replaces the default XML mapping with MyBatisPlus.2. MyBatisPlus version 3.3.2; UidGenerator version 1.0.0-Snapshot 3. Replace the default work_node table structure and the corresponding entity class 4. Replace the default DisposableWorkerIdAssigner and modifying injection mapper interfaces for the service

Ii. Dependencies and versions

Note: As UidGenerator default relies on MyBatis and MyBatis Spring dependencies, this is MyBatisPlus, so MyBatis and MyBatis Spring dependencies should be excluded.

<dependency>
	<groupId>com.baidu.fsg</groupId>
	<artifactId>uid-generator</artifactId>
	<version>${uid-generator.version}</version>
	<exclusions>
		<exclusion>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
		</exclusion>
		<exclusion>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>${mybatis-plus.version}</version>
</dependency>

Copy the code

Table structure and entity class replacement

CREATE TABLE `sy_worker_node`  (
  `work_node_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'primary key',
  `host_name` varchar(64)  NOT NULL COMMENT 'Host name',
  `port` varchar(64)  NOT NULL COMMENT 'port',
  `type` int(11) NOT NULL COMMENT 'Type (ACTUAL or CONTAINER)',
  `launch_date` date NOT NULL COMMENT 'Year month day',
  `modeified` timestamp(0) NOT NULL  COMMENT 'Modification time',
  `created` timestamp(0) NOT NULL  COMMENT 'Creation time',
  PRIMARY KEY (`work_node_id`) USING BTREE
) ;

Copy the code
@TableName("sy_worker_node")
@Getter
@Setter
public class WorkNode {

	@TableId(value = "work_node_id".type = IdType.AUTO)
	private Long work_node_id;

	@TableField(value = "host_name")
	private String host_name;

	@TableField(value = "port")
	private String port;

	@TableField(value = "type")
	private Integer type;

	@TableField(value = "launch_date")
	private Date launch_date;

	@TableField(value = "modeified")
	private Date modeified;

	@TableField(value = "created")
	private Date created;

}

Copy the code

4. Mapper interface

@Mapper
public interface WorkerNodeMapper extends BaseMapper<WorkNode>{

}

Copy the code

5. Interfaces and implementation classes

public interface IWorkNodeService extends IService<WorkNode>{ public WorkNode getWorkerNodeByHostPort(String host,String  port); public void addWorkerNode(WorkNode workNode); }Copy the code
@Service("workNodeService")
public class WorkNodeServiceImpl extends ServiceImpl<WorkerNodeMapper, WorkNode> implements IWorkNodeService{

	@Override
	public WorkNode getWorkerNodeByHostPort(String host, String port) {
		QueryWrapper<WorkNode> queryWrapper=new QueryWrapper<>();
		queryWrapper.lambda().eq(WorkNode::getHost_name, host).eq(WorkNode::getPort, port);
		returngetOne(queryWrapper); } @Override public void addWorkerNode(WorkNode workNode) { workNode.setCreated(new Date()); workNode.setModeified(new Date()); save(workNode); }}Copy the code

Configuration classes for UidGenerator

@ Configuration public class IdGeneratorConfiguration {/ * this class is in default on the basis of modified * / @ Bean public DisposableWorkerIdAssignerdisposableWorkerIdAssigner() {
		returnnew DisposableWorkerIdAssigner(); } @bean public CachedUidGenerator @bean public CachedUidGeneratorcachedUidGenerator() {
		CachedUidGenerator cachedUidGenerator = new CachedUidGenerator();
		cachedUidGenerator.setWorkerIdAssigner(disposableWorkerIdAssigner());
		returncachedUidGenerator; }}Copy the code
public class DisposableWorkerIdAssigner implements WorkerIdAssigner { private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class); /* @Autowired private WorkerNodeMapper workerNodeMapper; @autoWired Private IWorkNodeService workNodeService; /** * Assign worker id base on database.<p> * If there is host name & portin the environment, we considered that the node runs in Docker container<br>
     * Otherwise, the node runs on an actual machine.
     * 
     * @return assigned worker id
     */
    @Transactional
    public long assignWorkerId() {
        // build worker node entity
    	WorkNode workNode = buildWorkerNode();

        // add worker node for new (ignore the same IP + PORT)
        workNodeService.addWorkerNode(workNode);
        LOGGER.info("Add worker node:" + workNode);

        return workNode.getWork_node_id();
    }

    /**
     * Build worker node entity by IP and PORT
     */
    private WorkNode buildWorkerNode() {
    	WorkNode workNode = new WorkNode();
        if (DockerUtils.isDocker()) {
        	workNode.setType(WorkerNodeType.CONTAINER.value());
        	workNode.setHost_name(DockerUtils.getDockerHost());
        	workNode.setPort(DockerUtils.getDockerPort());
        	workNode.setLaunch_date(new Date());

        } else {
        	workNode.setType(WorkerNodeType.ACTUAL.value());
        	workNode.setHost_name(NetUtils.getLocalAddress());
            workNode.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
            workNode.setLaunch_date(new Date());
        }

        returnworkNode; }}Copy the code

Seven, test classes

@restController Public class IndexController {// Get the instance injected in the configuration class from the container @autoWired private UidGenerator UidGenerator; @GetMapping("/index")
	public String index(){
		System.err.println(uidGenerator.getUID());
		return "success"; }}Copy the code

Test results:

Eight, summary

  1. The first step is to create a table structure that inserts one piece of data each time the service is started
  2. Replace the default DisposableWorkerIdAssigner and modifies instance injection
  3. Inject the generator of the ID and the required instance into the configuration class

The last

Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!