hutool包的Snowflake类
分布式的 SNOWFLAKE_WORKID
单例的Snowflake
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Collections;
@Component
public class IdUtils {
@Autowired
private RedissonClient redissonClient;
private final String applicationName;
public IdUtils(@Value("${spring.application.name}") String applicationName) {
this.applicationName = applicationName;
}
private static Snowflake SNOWFLAKE = null;
public static Long getNextId() {
return SNOWFLAKE.nextId();
}
/**
* 自定义workerId,保证该应用的ID不会重复
*
* @return 新的id生成器
*/
@Bean
public void defaultSnowflake() {
String workerName = applicationName + "-order-worker-id";
Long SNOWFLAKE_WORKID = this.getWorkerId(workerName);
SNOWFLAKE = IdUtil.getSnowflake(SNOWFLAKE_WORKID, 1);
}
/**
* 容器环境生成workid 并redis缓存
*
* @param key
* @return
*/
public Long getWorkerId(String key) {
String luaScript = "local isExist = redis.call('exists', KEYS[1])\n" +
"if isExist == 1\n" +
"then\n" +
" local workerId = redis.call('get', KEYS[1])\n" +
" workerId = (workerId + 1) % 31\n" +
" redis.call('set', KEYS[1], workerId)\n" +
" return workerId\n" +
"else\n" +
" redis.call('set', KEYS[1], 0)\n" +
" return 0\n" +
"end";
RScript rScript = redissonClient.getScript();
Long result = rScript.eval(RScript.Mode.READ_WRITE, luaScript, RScript.ReturnType.INTEGER, Collections.singletonList(key));
return result;
}
}
v2版本
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Component
public class SnowFlakeUtilV2 {
private static Snowflake SNOWFLAKE = null;
private static final Logger LOGGER = LoggerFactory.getLogger(SnowFlakeUtil.class);
public static Long getNextId() {
return SNOWFLAKE.nextId();
}
@Bean
public void getSnowflakeId(){
//方式二:根据IP和hostName获取workId和dataCenterId
long workId = this.getWorkId();
long dataCenterId = this.getDataCenterId();
SNOWFLAKE = IdUtil.getSnowflake(workId, dataCenterId);
}
/**
* 根据IP Address 生成workId
*
* @return
*/
private long getWorkId() {
try {
String hostAddress = Inet4Address.getLocalHost().getHostAddress();
LOGGER.info("hostAddress========={}", hostAddress);
int[] ints = StringUtils.toCodePoints(hostAddress);
int sums = 0;
for (int b : ints) {
sums += b;
}
return (long) (sums % 32);
} catch (UnknownHostException e) {
LOGGER.error("根据IP获取workId失败。", e);
// 如果获取失败,则使用随机数备用
return RandomUtils.nextLong(0, 31);
}
}
/**
* 根据HostName 生成dataCenterId
* @return
*/
private long getDataCenterId() {
String hostName = getHostName();
LOGGER.info("hostName========={}", hostName);
int[] ints = StringUtils.toCodePoints(hostName);
int sums = 0;
for (int i : ints) {
sums += i;
}
return (long) (sums % 32);
}
/**
* 获取 hostName
* SystemUtils.getHostName() 在mac系统为空处理
* @return
*/
public static String getHostName() {
//获取当前操作系统名称,例如:windows xp,linux 等
String osName = System.getProperty("os.name");
String hostName = null;
if(!StringUtils.startsWithIgnoreCase(osName,"mac")){
hostName = SystemUtils.getHostName();
}else{
try {
hostName = InetAddress.getLocalHost().getHostName().toUpperCase();
} catch (UnknownHostException e) {
hostName = "N/A";
LOGGER.error("获取 hostName错误:", e);
}
}
return hostName;
}
}