[ISSUE #11994]修复HttpRequestInstanceBuilderTest出现的空指针问题,优化SnowFlakeInstanceIdGenerator初始化流程 (#11995)

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

* refactor: Optimize the initialization process of SnowFlakeInstanceIdGenerator

* refactor: optimize the initialization process of SnowFlakeInstanceIdGenerator.
This commit is contained in:
cx 2024-04-23 09:31:11 +08:00 committed by GitHub
parent 96814ff00d
commit 720519b1dc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 22 additions and 4 deletions

View File

@ -31,13 +31,28 @@ import static com.alibaba.nacos.api.common.Constants.SNOWFLAKE_INSTANCE_ID_GENER
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();

View File

@ -21,12 +21,14 @@ import com.alibaba.nacos.api.naming.CommonParams;
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;
@ -54,6 +56,7 @@ public class HttpRequestInstanceBuilderTest {
@BeforeClass
public static void setUpBeforeClass() {
NacosServiceLoader.load(InstanceExtensionHandler.class);
EnvUtil.setEnvironment(new StandardEnvironment());
}
@Before