tk.mybatis GenId 雪花算法 workerId datacenterId yml配置

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属性也可以用这种方法

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值