Commit 837f1616 by Future

雪花id生成调整

parent 9dcff60d
package com.wecloud.utils;
import cn.hutool.core.lang.Snowflake;
import com.wecloud.im.ws.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.net.Inet4Address;
import java.net.UnknownHostException;
/**
* 雪花算法 获取id工具类
......@@ -15,14 +17,11 @@ import javax.annotation.PostConstruct;
@Component
public class SnowflakeUtil {
private static SnowflakeUtil snowflakeUtil;
/**
* workerId, dataCenterId动态获取
* 12位序列号部分,支持同一毫秒内同一个节点可以生成4096个ID, 在目前一段不用做成动态获取服务器ID
*/
private static volatile Snowflake SNOWFLAKE = null;
@Autowired
private RedisUtils redisUtils;
/**
* 多线程中加synchronized 保证不会获取重复id
......@@ -34,12 +33,7 @@ public class SnowflakeUtil {
if (SNOWFLAKE == null) {
synchronized (SnowflakeUtil.class) {
if (SNOWFLAKE == null) {
// workerId通过redis获取
long workerId = snowflakeUtil.redisUtils.incr("workerId", 1);
// redisUtils不需要用了,释放回收掉
snowflakeUtil.redisUtils = null;
SNOWFLAKE = new Snowflake(workerId, 1L);
SNOWFLAKE = new Snowflake(SnowflakeUtil.getWorkId(), SnowflakeUtil.getDataCenterId());
}
}
}
......@@ -47,11 +41,31 @@ public class SnowflakeUtil {
}
/**
* 静态方法里调用spring注入的方法
* workId通过本机ip计算获得
* @return
*/
@PostConstruct
public void init() {
snowflakeUtil = this;
snowflakeUtil.redisUtils = this.redisUtils;
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);
}
}
private static Long getDataCenterId(){
int[] ints = StringUtils.toCodePoints(SystemUtils.getHostName());
int sums = 0;
for (int i: ints) {
sums += i;
}
return (long)(sums % 32);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment