Skip to content

Commit

Permalink
*修复springboot注册插件获取spring.application.name的bug
Browse files Browse the repository at this point in the history
  • Loading branch information
provenceee committed Apr 20, 2023
1 parent ee8c296 commit d061c1a
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 25 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
<gpg.plugin.version>3.0.1</gpg.plugin.version>
<javadoc.plugin.version>3.3.2</javadoc.plugin.version>
<nexus.staging.plugin.version>1.6.7</nexus.staging.plugin.version>
<frontend.plugin.version>1.12.1</frontend.plugin.version>

<sermant.name>sermant-agent</sermant.name>
<sermant.basedir>${pom.basedir}</sermant.basedir>
Expand Down Expand Up @@ -285,6 +286,11 @@
<version>${mockito-inline.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>${frontend.plugin.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<profiles>
Expand Down
1 change: 0 additions & 1 deletion sermant-backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<io.netty.version>4.1.86.Final</io.netty.version>
<spring-boot.version>2.6.1</spring-boot.version>
<frontend-maven-plugin.version>1.12.1</frontend-maven-plugin.version>
<protobuf-java.version>3.9.1</protobuf-java.version>
<lombok.version>1.18.12</lombok.version>
<fastjson.version>1.2.83</fastjson.version>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class SpringEnvironmentInfoDeclarer extends BaseDeclarer {

private static final String INTERCEPT_CLASS = SpringEnvironmentInfoInterceptor.class.getCanonicalName();

private static final String METHOD_NAME = "prepareEnvironment";
private static final String METHOD_NAME = "applyInitializers";

@Override
public ClassMatcher getClassMatcher() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,14 @@ public void setStatus(String status) {
public void setId(String id) {
this.id = id;
}

@Override
public String toString() {
return "{"
+ "serviceName='" + serviceName + '\''
+ ", port=" + port
+ ", metadata=" + metadata
+ ", status='" + status + '\''
+ '}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,27 @@

package com.huawei.discovery.interceptors;

import com.huawei.discovery.entity.DefaultServiceInstance;
import com.huawei.discovery.entity.RegisterContext;
import com.huawei.discovery.entity.ServiceInstance.Status;
import com.huawei.discovery.utils.HostIpAddressUtils;

import com.huaweicloud.sermant.core.common.LoggerFactory;
import com.huaweicloud.sermant.core.config.ConfigManager;
import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext;
import com.huaweicloud.sermant.core.plugin.agent.interceptor.Interceptor;
import com.huaweicloud.sermant.core.plugin.config.ServiceMeta;
import com.huaweicloud.sermant.core.utils.StringUtils;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* 结束阶段设置服务相关信息
Expand All @@ -38,9 +45,11 @@
* @since 2022-10-09
*/
public class SpringEnvironmentInfoInterceptor implements Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger();

private static final int DEFAULT_PORT = 8080;

private static final String DEFAULT_APPLICATION_NAME = "default-application";
private static final String DEFAULT_SERVICE_NAME = "default-service";

@Override
public ExecuteContext before(ExecuteContext context) throws Exception {
Expand All @@ -49,10 +58,15 @@ public ExecuteContext before(ExecuteContext context) throws Exception {

@Override
public ExecuteContext after(ExecuteContext context) throws Exception {
Object result = context.getResult();
String ipAddress = HostIpAddressUtils.getHostAddress();
if (result instanceof ConfigurableEnvironment) {
this.setClientInfo((ConfigurableEnvironment) result, ipAddress);
Object[] arguments = context.getArguments();
if (arguments != null && arguments.length > 0) {
Object argument = arguments[0];
if (argument instanceof ConfigurableApplicationContext) {
ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) argument;

// 这里有可能会进入多次,多次进入时,后面的优先级高于前面,所以直接覆盖更新就行
this.setClientInfo(applicationContext.getEnvironment(), HostIpAddressUtils.getHostAddress());
}
}
return context;
}
Expand All @@ -65,23 +79,45 @@ public ExecuteContext onThrow(ExecuteContext context) throws Exception {
private void setClientInfo(ConfigurableEnvironment environment, String ipAddress) {
String address = environment.getProperty("server.address");
String port = environment.getProperty("server.port");
String applicationName = environment.getProperty("spring.application.name");
RegisterContext.INSTANCE.getServiceInstance().setHost(StringUtils.isEmpty(address) ? ipAddress : address);
RegisterContext.INSTANCE.getServiceInstance().setIp(StringUtils.isEmpty(address) ? ipAddress : address);
RegisterContext.INSTANCE.getServiceInstance()
.setPort(StringUtils.isEmpty(port) ? DEFAULT_PORT : Integer.parseInt(port));
RegisterContext.INSTANCE.getServiceInstance()
.setServiceName(StringUtils.isEmpty(applicationName) ? DEFAULT_APPLICATION_NAME : applicationName);
RegisterContext.INSTANCE.getServiceInstance().setId(RegisterContext.INSTANCE.getServiceInstance().getIp()
+ ":" + RegisterContext.INSTANCE.getServiceInstance().getPort());
RegisterContext.INSTANCE.getServiceInstance().setStatus(Status.UP.name());
if (RegisterContext.INSTANCE.getServiceInstance().getMetadata() == null) {
String serviceName = environment.getProperty("spring.application.name");
DefaultServiceInstance instance = RegisterContext.INSTANCE.getServiceInstance();
instance.setHost(StringUtils.isEmpty(address) ? ipAddress : address);
instance.setIp(StringUtils.isEmpty(address) ? ipAddress : address);
instance.setPort(getProperty(instance.getPort(), value -> value == 0, port, Integer::parseInt, DEFAULT_PORT));
instance.setServiceName(getProperty(instance.getServiceName(), Objects::isNull, serviceName, value -> value,
DEFAULT_SERVICE_NAME));
instance.setId(instance.getIp() + ":" + instance.getPort());
instance.setStatus(Status.UP.name());
if (instance.getMetadata() == null) {
Map<String, String> metadata = new HashMap<String, String>();
ServiceMeta serviceMeta = ConfigManager.getConfig(ServiceMeta.class);
if (StringUtils.isExist(serviceMeta.getZone())) {
metadata.put("zone", serviceMeta.getZone());
}
RegisterContext.INSTANCE.getServiceInstance().setMetadata(metadata);
LOGGER.log(Level.INFO, "Instance''s metadata is {0}.", metadata);
instance.setMetadata(metadata);
}
LOGGER.log(Level.INFO, "Instance''s msg is {0}.", instance);
}

private <T> T getProperty(T currentProperty, Function<T, Boolean> judgmentMapper, String env,
Function<String, T> envMapper, T defaultValue) {
// environment.getProperty不为空,覆盖
if (!StringUtils.isBlank(env)) {
T property = envMapper.apply(env);
LOGGER.log(Level.INFO, "Env is not null, current property is {0}, will return {1}.",
new Object[]{currentProperty, property});
return property;
}

// environment.getProperty为空且当前值为null,存入默认值
if (judgmentMapper.apply(currentProperty)) {
LOGGER.log(Level.INFO, "Env is null, current property is invalid, will return {0}.", defaultValue);
return defaultValue;
}

// environment.getProperty为空且当前存在值,返回当前值
LOGGER.log(Level.INFO, "Env is null, current property is valid, will return {0}.", currentProperty);
return currentProperty;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,17 @@

package com.huawei.discovery.interceptors;

import com.huawei.discovery.entity.RegisterContext;

import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import com.huawei.discovery.entity.RegisterContext;
import com.huaweicloud.sermant.core.plugin.agent.entity.ExecuteContext;

public class SpringEnvironmentInfoInterceptorTest extends BaseTest {

private SpringEnvironmentInfoInterceptor interceptor;

private final Object[] arguments;
Expand All @@ -34,7 +35,7 @@ public class SpringEnvironmentInfoInterceptorTest extends BaseTest {
* 构造方法
*/
public SpringEnvironmentInfoInterceptorTest() {
arguments = new Object[2];
arguments = new Object[1];
}

@Override
Expand All @@ -50,7 +51,9 @@ public void testSpringEnvironmentInfoInterceptor() throws Exception {
Mockito.when(environment.getProperty("server.address")).thenReturn("192.168.0.157");
Mockito.when(environment.getProperty("server.port")).thenReturn("8010");
Mockito.when(environment.getProperty("spring.application.name")).thenReturn("zookeeper-provider-demo");
context.afterMethod(environment, null);
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
applicationContext.setEnvironment(environment);
arguments[0] = applicationContext;
interceptor.after(context);
Assert.assertEquals(RegisterContext.INSTANCE.getServiceInstance().getServiceName(), "zookeeper-provider-demo");
}
Expand Down

0 comments on commit d061c1a

Please sign in to comment.