配置 workId 和 datacenterId
设置工作机器ID(workerId)和数据中心ID(datacenterId),这两个参数用于确保在分布式环境中生成的ID是唯一的。使用配置 yaml 文件的方式获取,配置方式参考:https://blog.csdn.net/qq_35201802/article/details/143727005
my-app:snowflake:workerId: 1datacenterId: 1
初始化雪花算法生成器
package com.shore.my_spring_demo.web.config;import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;@Configuration
public class IdGeneratorConfig {@Resourceprivate CustomSnowflakeConfig customSnowflakeConfig;@Beanpublic Snowflake snowflakeIdGenerator() {return IdUtil.getSnowflake(customSnowflakeConfig.getWorkerId(), customSnowflakeConfig.getDatacenterId());}
}
生成唯一 id
在服务层或控制器层中,注入Snowflake
实例,并调用它的nextId()
方法来生成唯一ID。
package com.shore.my_spring_demo.service.id.impl;import cn.hutool.core.lang.Snowflake;
import com.shore.my_spring_demo.service.id.IdService;
import org.springframework.stereotype.Service;import javax.annotation.Resource;@Service
public class IdServiceImpl implements IdService {@Resourceprivate Snowflake snowflake;@Overridepublic Long generateId() {return snowflake.nextId();}
}