配置IdWorker ID生成工具
dworker是一个ID生成工具,可以生成一个全局唯一的长整形ID。也支持分布式环境下的使用。idworker采用了Snowflake算法,并在此基础上增加了奇偶抖动功能,避免在低并发的环境下生成全是偶数的情况。
1.IdWorkerProperties 为配置类,用于封装 application.yml中配置信息
IdWorkerConfig 根据配置类IDWorkerProperties 构建IdWorker实例
2.application.yml配置IdWorker需要的参数
3.编写IdWorkerProperties,加载配置文件
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/** 配置文件封装类,用于存放application.yml配置文件中自定义内容
* Created by liangtong.
*/
@ConfigurationProperties(prefix = "sc.worker")
@Data
public class IdWorkProperties {
private Integer workerId;
private Integer datacenterId;
}
4.编写IdWorkerConfig,让整个环境有IdWorker实例
import com.czxy.changgou.utils.IdWorker;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/** IdWorker实例对象的配置类
* Created by liangtong.
*/
@EnableConfigurationProperties(IdWorkProperties.class)
@Component
public class IdWorkConfig {
@Bean
public IdWorker createWorker(IdWorkProperties idWorkProperties){
return new IdWorker(idWorkProperties.getWorkerId(),idWorkProperties.getDatacenterId());
}
}
5.调用
因为之前的步骤我们已经将idwork工具类交由Spring进行管理
如果使用只需要@Resource注解填充
然后调用nextId方法即可.
@Resource
private IdWorker idWorker;
public void test1(){
idWorker.nextId();
}