tk.mybatis GenId 雪花算法 workerId datacenterId yml配置
配置不同的工作号服务号避免生成重复id,使用yml配置文件进行配置,本来想使用properties的但是就这一个需求感觉没必要,当然用properties更方便;
一开始想直接将属性值注入,但是genId调用的时候是自己实例化的不会用Spring容器里的对象,所以不行;如果使用静态的那又不能直接注入,但是我们可以使用环境对象进行读取
github-demo地址
//GenId
package airport.cargos.web_common_special_goods_identify.utils;
import airport.cargos.web_common_special_goods_identify.conf.GenIdConfig;
import tk.mybatis.mapper.genid.GenId;
public class UUIDGenId implements GenId {
private SnowflakeIdWorker snowFlakeIdWorker ;
public UUIDGenId(){
this.snowFlakeIdWorker = new SnowflakeIdWorker(GenIdConfig.getWorkerId(),GenIdConfig.getDatacenterId());
}
public Long genId(String table, String column) {
return snowFlakeIdWorker.nextId();
}
}
//配置类,可以直接放到GenId里,但是为了单一职责,单独写
package airport.cargos.web_common_special_goods_identify.conf;
import org.springframework.core.env.Environment;
public class GenIdConfig {
private static Environment environment;
public static void setEnvironment(Environment env) {
environment = env;
}
public static Long getWorkerId() {
return environment.getProperty("genId.workerId",Long.class);
}
public static Long getDatacenterId() {
return environment.getProperty("genId.datacenterId",Long.class);
}
}
//监听应用预备事件,发生在component加入容器后
package airport.cargos.web_common_special_goods_identify.event;
import airport.cargos.web_common_special_goods_identify.conf.GenIdConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class GenIdConfigurator implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private ApplicationContext applicationContext;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
GenIdConfig.setEnvironment(applicationContext.getEnvironment());
}
}
genId:
workerId: 10
datacenterId: 10
所以我们的配置信息如果想注入到static属性也可以用这种方法