Commit 837f1616 by Future

雪花id生成调整

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