@Component @Slf4j public class SnowflakeUtil { private Snowflake snowflake = IdUtil.createSnowflake(getWorkId(), getDataCenterId()); public synchronized long snowflakeId() { return snowflake.nextId(); } public synchronized long snowflakeId(long workerId, long dataCenterId) { Snowflake snowflake = IdUtil.createSnowflake(workerId, dataCenterId); return snowflake.nextId(); } /** * @Author gj * @Description 获取机器id * @Params * @Return * @Date 2021/5/26 13:52 */ private static Long getWorkId() { try { String hostAddress = Inet4Address.getLocalHost().getHostAddress(); int[] ints = StringUtils.toCodePoints(hostAddress); int sums = 0; for (int b : ints) { sums += b; } return (long) (sums % 32); } catch (UnknownHostException e) { // 如果获取失败,则使用随机数备用 return RandomUtils.nextLong(0, 31); } } /** * @Author gj * @Description获取数据id * @Params * @Return * @Date 2021/5/26 13:52 */ protected static long getDataCenterId() { long id = 0L; try { //获取本机(或者服务器ip地址) //DESKTOP-123SDAD/192.168.1.87 InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); //一般不是null会进入else if (network == null) { id = 1L; } else { //获取物理网卡地址 byte[] mac = network.getHardwareAddress(); if (null != mac) { id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6; id = id % (31 + 1); } } } catch (Exception e) { return RandomUtils.nextLong(0, 31); } return id; } }
pom
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-core</artifactId> <version>${hutool.version}</version> </dependency>