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);
}
博客内容讲述了在使用Spring Boot时遇到的一个Bean创建异常,具体涉及到Hutool库中的Snowflake ID生成器。问题源于生成的workerId超出了Snowflake算法允许的范围。通过调整workerId的计算方式,将其转换为适合的范围,解决了启动异常。修复后的代码展示了如何正确初始化Snowflake实例,确保workerId在0-31之间。

3191

被折叠的 条评论
为什么被折叠?



