UidGenerator springboot2集成篇
uid-generator
官网集成文档:
https://github.com/baidu/uid-generator/blob/master/README.zh_cn.md
由于并没有提供springboot集成版本,网上找的都缺少必须步骤,我这里梳理一下详细的uid-generator与springboot2集成的步骤
uid-generator与springboot2集成初始化
创建一个MySQL数据库名称为baiduUidGenerator
执行如下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;
uid-generator与springboot2集成
初始化一个springboot项目,并修改pom文件如下
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<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>
<scope>runtime</scope>
<version>8.0.12</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--必须放在最后-->
<dependency>
<groupId>com.baidu.fsg</groupId>
<artifactId>uid-generator</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
修改配置文件application.properties(注意MySQL地址、数据库名称账户等于之前建表的保持一致)
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=true
新建UidGenService,内容如下
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();
}
}
与启动类同级目录新建WorkerNodeMapper内容如下(下面的两步是解决UidGenerator与springboot集成出现的无法正常注入bean的问题)
/*
* 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);
}
与启动类同级目录新建DisposableWorkerIdAssigner内容如下
/*
* 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;
}
}
springboot启动类上添加注解,org.zxp.uidgeneratortest
需要更新为你的工程路径
@RestController
@ComponentScan(basePackages = {"org.zxp.uidgeneratortest","com.baidu.fsg"})
@MapperScan("org.zxp.uidgeneratortest")
resources下创建mapper目录(为了同配置文件路径一致)并创建文件WorkerNodeMapper.xml,内容如下:
<?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>
springboot启动类添加如下方法(做一些代替xml的配置以及测试的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;
}
测试
启动springboot工程
访问:http://localhost:9999/getuid
返回:3686802606946000922
成功!
UidGenerator springboot2集成篇的更多相关文章
- Activiti(二) springBoot2集成activiti,集成activiti在线设计器
摘要 本篇随笔主要记录springBoot2集成activiti流程引擎,并且嵌入activiti的在线设计器,可以通过浏览器直接编辑出我们需要的流程,不需要通过eclipse或者IDEA的actiB ...
- 用好lua+unity,让性能飞起来——luajit集成篇/平台相关篇
luajit集成篇 大家都知道luajit比原生lua快,快在jit这三个字上. 但实际情况是,luajit的行为十分复杂.尤其jit并不是一个简单的把代码翻译成机器码的机制,背后有很多会影响性能的因 ...
- 持续集成篇_08_Hudson持续集成服务器的使用(自动化编译、分析、打包、部署)
持续集成篇_08_Hudson持续集成服务器的使用(自动化编译.分析.打包.部署) 1.创建任务 svn用户验证 验证通过 *****五颗*表示每分钟检查svn路径是否有变更,有变更就会重新构建,相当 ...
- springboot2集成pagehelper
springboot2集成pagehelper超级简单,本示例直接抄袭官方示例,仅将数据库由H2改成MySQL而已. 1. pom.xml <?xml version="1.0&quo ...
- 微信支付JSAPI模式及退款CodeIgniter集成篇
微信支付接口文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_1 首先你得知道这个jsapi是不能离开微信进行调用支付的,明白 ...
- 机器学习 - pycharm, tensorflow集成篇
继续上篇的pyspark集成后,我们再来看看当今热的不得了的tensorflow是如何继承进pycharm环境的 参考: http://blog.csdn.net/include1224/articl ...
- Jenkins +git +python 进行持续集成进行接口测试(接口测试jenkins持续集成篇)
使用jenkins+git+python脚本进行持续集成的接口测试,在jenkins平台,利用插件等,把管理代码的git仓库的代码更新下来进行持续接口测试,python进行开发测试脚本,git进行远程 ...
- Jmeter 接口测试知识梳理——持续集成篇
Jmeter 使用也有很长时间了,但是一直没有做一下知识梳理,近期会对公司同事做一下这方面的培训,借此机会,把使用过程中应用到的知识,或是遇到的问题,整理出来,方便大家学习! Jmeter + Ant ...
- 机器学习 - 开发环境安装pycharm + tensorflow集成篇
继续上篇的pyspark集成后,我们再来看看当今热的不得了的tensorflow是如何继承进pycharm环境的 参考: http://blog.csdn.net/include1224/articl ...
随机推荐
- 用webAudio和canvas实现音频可视化
前两天遇到了要显示音频波形图的需求,因为时间紧,就直接用了wavesufer.js,这两天有空,就研究了一下怎么用webAudio实现音频的可视化. 大致流程是对音源进行解析,解析得到的数据是个频谱数 ...
- H3C保存当前配置--用户图示(console)以上
<H3C>save //此种保存只默认保存为Startup.cfg ,系统默认是加载此文件 The current configuration will be writte ...
- 2018-2-13-win10-uwp-异步进度条
title author date CreateTime categories win10 uwp 异步进度条 lindexi 2018-2-13 17:23:3 +0800 2018-2-13 17 ...
- 个人脚手架搭建 -- charmingsong-cli
个人脚手架搭建 -- charmingsong-cli 目的 为了解决多次构建相同功能的项目,在一定程度上需要定制化以及私有化设置 设计 问题 为什么不用现成的脚手架生成? 如果利用vue或者reac ...
- .net core允许跨域
// 设置允许所有来源跨域 app.UseCors(options => { options.AllowAnyHeader(); options.AllowAnyMethod(); option ...
- Linux普通用户执行特定的命令配置
最近处理了一个二级CASE,驻场运维的初级工程师安装软件的时候执行了yum update,导致用户生产系统的glibc也升级了,使得用户的生产调度软件无法使用.研究了两三天,最靠谱的做法如下: Ste ...
- linux中的文件类型标记方法
在ls -l显示的详细信息中有以下信息: -rw-r--r-- drwxr-xr-x 一共10个字符,第一个字符表示文件类型,后面9个字符分成3组表示文件权限.前三个表示属主(拥有者)对文件的权限,中 ...
- java面试-反射
1.什么是反射?有什么优缺点? 反射就是动态加载对象,并对对象进行剖析.在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法.对于任意一个对象,都能够调用它的任意一个方法.这种动态获取信 ...
- 怎么彻底删除用友通T3财务软件?
[问题现象]怎么彻底删除用友通T3财务软件? [原因分析]通过"添加或删除程序"无法正常卸载用友通T3,也尝试了360安全卫士强力卸载,都无法完全卸载,有没有办法可以彻底删除用友通 ...
- JVM执行引擎
1.概述 执行引擎是jvm核心组成部分之一,建立在物理器,硬件和操作系统层面之上,引擎在执行代码时会有解释执行和编译执行两种选择,输入字节码文件,字节码解析输出结果. 2.栈帧 栈帧是用于支持虚拟机进 ...