springboot中使用自定义的雪花id
物料准备:
-
引入hutool依赖
-
自定义1个IdGenerator类
-
测试使用IdGenerator来生成雪花id
引入hutool依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.11</version>
</dependency>
自定义1个IdGenerator类
@Slf4j
@Component
public class IdGenerator {
private long workerId = 0;
@PostConstruct
void init() {
try {
workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
log.info("当前机器 workerId: {}", workerId);
} catch (Exception e) {
log.warn("获取机器 ID 失败", e);
workerId = NetUtil.getLocalhost().hashCode();
log.info("当前机器 workerId: {}", workerId);
}
}
private Snowflake snowflake = IdUtil.getSnowflake(workerId, 1);
public synchronized long snowflakeId() {
return snowflake.nextId();
}
}
测试使用IdGenerator来生成雪花id
@SpringBootTest
class KnowWikiBackendApplicationTests {
@Autowired
private IdGenerator idGenerator;
@Test
void test531(){
long l = idGenerator.snowflakeId();
System.out.println(l); //1663875826917179392
//1663876143100592128
}
}