Skip to content

Commit

Permalink
[ISSUE alibaba#11994]修复HttpRequestInstanceBuilderTest出现的空指针问题,优化SnowF…
Browse files Browse the repository at this point in the history
…lakeInstanceIdGenerator初始化流程 (alibaba#11995)

* [ISSUE alibaba#11994] fix: Initialize EnvUtil's variable environment in HttpRequestInstanceBuilderTest

* refactor: Optimize the initialization process of SnowFlakeInstanceIdGenerator

* refactor: optimize the initialization process of SnowFlakeInstanceIdGenerator.
  • Loading branch information
llzcx authored and [email protected] committed Apr 25, 2024
1 parent 98227bb commit 3fc4efc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,28 @@
public class SnowFlakeInstanceIdGenerator implements InstanceIdGenerator {

private static final SnowFlowerIdGenerator SNOW_FLOWER_ID_GENERATOR = new SnowFlowerIdGenerator();

static {
SNOW_FLOWER_ID_GENERATOR.init();

private static volatile boolean initialize = false;

private static final Object LOCK = new Object();

/**
* initialize the workerId and ensure that it is only initialized once.
*/
private void ensureWorkerIdInitialization() {
if (!initialize) {
synchronized (LOCK) {
if (!initialize) {
SNOW_FLOWER_ID_GENERATOR.init();
initialize = true;
}
}
}
}

@Override
public String generateInstanceId(Instance instance) {
ensureWorkerIdInitialization();
return SNOW_FLOWER_ID_GENERATOR.nextId() + NAMING_INSTANCE_ID_SPLITTER
+ instance.getClusterName() + NAMING_INSTANCE_ID_SPLITTER
+ instance.getServiceName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.spi.NacosServiceLoader;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.env.StandardEnvironment;

import javax.servlet.http.HttpServletRequest;

Expand Down Expand Up @@ -54,6 +56,7 @@ public class HttpRequestInstanceBuilderTest {
@BeforeClass
public static void setUpBeforeClass() {
NacosServiceLoader.load(InstanceExtensionHandler.class);
EnvUtil.setEnvironment(new StandardEnvironment());
}

@Before
Expand Down

0 comments on commit 3fc4efc

Please sign in to comment.