springboot分布式id,基于snowflake的分布式统一id生成工具
如不设置表自增长,那么此处唯一id可设置 IdType.ASSIGN_ID,单机版用mybatis默认的雪花算法IdentifierGenerator 即可,集群版推荐使用zookeeper,snowflake的分布式统一ID生成工具idworker .
<!--pom添加包idworker-->
<dependency>
<groupId>com.imadcn.framework</groupId>
<artifactId>idworker</artifactId>
<version>1.6.0</version>
<exclusions>
<exclusion>
<artifactId>curator-client</artifactId>
<groupId>org.apache.curator</groupId>
</exclusion>
</exclusions>
</dependency>
package com.cn.dydatasource;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.ImadcnIdentifierGenerator;
import com.github.pagehelper.util.StringUtil;
import com.imadcn.framework.idworker.config.ApplicationConfiguration;
import com.imadcn.framework.idworker.config.ZookeeperConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 分布式id问题
*/
@Configuration()
@ConfigurationProperties(prefix = "mybatis-plus.zookeeper")
public class MybatisConfig {
private String serverLists;
public String getServerLists() {
return serverLists;
}
public void setServerLists(String serverLists) {
this.serverLists = serverLists;
}
//zookeeper 解决分布式id重复问题
//默认是 根据ip来进行 增长的 如果ip相同 同一台机器 生成的id是不会重复的 所以同一个业务写入集部署情况 应放置在不同的服务器
@Bean
public IdentifierGenerator idGenerator() {
if(!StringUtil.isEmpty(serverLists)){
ZookeeperConfiguration zkConfig = new ZookeeperConfiguration();
zkConfig.setServerLists(serverLists);
zkConfig.setSessionTimeoutMilliseconds(3000);
ApplicationConfiguration applicationConfiguration=new ApplicationConfiguration();
applicationConfiguration.setSerialize("fastjson");
return new ImadcnIdentifierGenerator(zkConfig,applicationConfiguration);
}
return new DefaultIdentifierGenerator();
}
}
注:application.yml中需添加zookeeper配置