记一次使用hutool工具生成雪花算法的报错

博客内容讲述了在使用Spring Boot时遇到的一个Bean创建异常,具体涉及到Hutool库中的Snowflake ID生成器。问题源于生成的workerId超出了Snowflake算法允许的范围。通过调整workerId的计算方式,将其转换为适合的范围,解决了启动异常。修复后的代码展示了如何正确初始化Snowflake实例,确保workerId在0-31之间。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'snowFlake': Invocation of init method failed; nested exception is java.lang.RuntimeException: cn.hutool.core.exceptions.UtilException: Instance class [class cn.hutool.core.lang.Snowflake] error!

cn.hutool.core.exceptions.UtilException: Instance class [class cn.hutool.core.lang.Snowflake] error!

源代码:

    private Snowflake snowflake;

    @PostConstruct
    private void init(){
        Long workerId= NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        Long dataCenterId = 1L;
        snowflake = IdUtil.getSnowflake(workerId, dataCenterId);
    }

在spring容器启动时报了上面的错

原因是生成workerId超出了源码里规定的范围

    public Snowflake(Date epochDate, long workerId, long dataCenterId, boolean isUseSystemClock, long timeOffset) {
        this.sequence = 0L;
        this.lastTimestamp = -1L;
        if (null != epochDate) {
            this.twepoch = epochDate.getTime();
        } else {
            this.twepoch = DEFAULT_TWEPOCH;
        }

        if (workerId <= 31L && workerId >= 0L) {
            if (dataCenterId <= 31L && dataCenterId >= 0L) {
                this.workerId = workerId;
                this.dataCenterId = dataCenterId;
                this.useSystemClock = isUseSystemClock;
                this.timeOffset = timeOffset;
            } else {
                throw new IllegalArgumentException(StrUtil.format("datacenter Id can't be greater than {} or less than 0", new Object[]{31L}));
            }

规定workerId范围在0L-31L之间,超出会报异常

将workerId进行处理

workerId = workerId >> 16 & 31;

修改后代码:

    private Snowflake snowflake;

    @PostConstruct
    private void init() {
        Long workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()) >> 16 & 31;
        Long dataCenterId = 1L;
        snowflake = IdUtil.getSnowflake(workerId, dataCenterId);
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值