美团Leaf分布式ID生成器整和SpringBoot

Leaf

There are no two identical leaves in the world.

世界上没有两片完全相同的树叶。

​ — 莱布尼茨

 1.git项目

先将项目克隆到本地,打包到Maven仓库

git clone git@github.com:Meituan-Dianping/Leaf.git
git checkout feature/spring-boot-starter
cd leaf
mvn clean install -Dmaven.test.skip=true 

 2.添加Maven依赖

<dependency>
	<artifactId>leaf-boot-starter</artifactId>
    <groupId>com.sankuai.inf.leaf</groupId>
    <version>1.0.1-RELEASE</version>
</dependency>

3.添加配置文件

#号段模式
leaf.name=com.sankuai.leaf.opensource.test
leaf.segment.enable=false
#leaf.segment.url=
#leaf.segment.username=
#leaf.segment.password=
#雪花算法模式
leaf.snowflake.enable=false
#leaf.snowflake.address=
#leaf.snowflake.port=
配置项含义默认值
leaf.nameleaf 服务名
leaf.segment.enable是否开启号段模式false
leaf.jdbc.urlmysql 库地址
leaf.jdbc.usernamemysql 用户名
leaf.jdbc.passwordmysql 密码
leaf.snowflake.enable是否开启snowflake模式false
leaf.snowflake.zk.addresssnowflake模式下的zk地址
leaf.snowflake.portsnowflake模式下的服务注册端口

4.添加注解

//EnableLeafServer 开启leafserver
@SpringBootApplication
@EnableLeafServer
public class LeafdemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LeafdemoApplication.class, args);
	}
}
//直接使用 spring注入
public class T {
    @Autowired
    private SegmentService segmentService;
    @Autowired
    private SnowflakeService snowflakeService;
}

5.使用号段模式

5.1.创建数据库表

CREATE DATABASE leaf
CREATE TABLE `leaf_alloc` (
  `biz_tag` varchar(128)  NOT NULL DEFAULT '',
  `max_id` bigint(20) NOT NULL DEFAULT '1',
  `step` int(11) NOT NULL,
  `description` varchar(256)  DEFAULT NULL,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`biz_tag`)
) ENGINE=InnoDB;

insert into leaf_alloc(biz_tag, max_id, step, description) values('leaf-segment-test', 1, 2000, 'Test leaf Segment Mode Get Id')

5.2.修改配置文件

leaf.name=com.sankuai.leaf.opensource.test    #随意填写
leaf.segment.enable=true    #修改为true
#leaf.segment.url=    #填写url地址,这里必须使用MySQL5驱动
#leaf.segment.username=    #账号
#leaf.segment.password=    #密码

有能力可以去修改源代码,让其支持MySQL8

6.使用Snowflake模式

6.1.安装zookeeper3.5.6

这里就不说如何安装了,注意使用Docker安装存在问题,我试了多次代码连接均报错,建议使用Linux或者Windows,如果解决办法可以评论区交流

6.2.修改配置文件

leaf.snowflake.enable=true
#leaf.snowflake.address=127.0.0.1:2181    #根据实际地址修改
#leaf.snowflake.port=2222    #随机未使用端口

7.简化整合

可以尝试使用

https://github.com/guang19/leaf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值