refactor:optimize project and code. (#571)

pull/569/head
Haotian Zhang 2 years ago committed by GitHub
parent 7774b418e8
commit 8c9d0decb7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -33,3 +33,4 @@
- [Report the labels in request when report the result of invocation by Feign](https://github.com/Tencent/spring-cloud-tencent/pull/556) - [Report the labels in request when report the result of invocation by Feign](https://github.com/Tencent/spring-cloud-tencent/pull/556)
- [fix:fix heartbeat interval different configuration from polaris-java SDK.](https://github.com/Tencent/spring-cloud-tencent/pull/559) - [fix:fix heartbeat interval different configuration from polaris-java SDK.](https://github.com/Tencent/spring-cloud-tencent/pull/559)
- [Optimize: optimize report call result for restTemplate.](https://github.com/Tencent/spring-cloud-tencent/pull/565) - [Optimize: optimize report call result for restTemplate.](https://github.com/Tencent/spring-cloud-tencent/pull/565)
- [refactor:optimize project and code.](https://github.com/Tencent/spring-cloud-tencent/pull/571)

@ -132,7 +132,7 @@ public class MetadataTransferAutoConfiguration {
} }
@Bean @Bean
public SmartInitializingSingleton addEncodeTransferMedataInterceptorForRestTemplate(EncodeTransferMedataRestTemplateInterceptor interceptor) { public SmartInitializingSingleton addEncodeTransferMetadataInterceptorForRestTemplate(EncodeTransferMedataRestTemplateInterceptor interceptor) {
return () -> restTemplates.forEach(restTemplate -> { return () -> restTemplates.forEach(restTemplate -> {
List<ClientHttpRequestInterceptor> list = new ArrayList<>(restTemplate.getInterceptors()); List<ClientHttpRequestInterceptor> list = new ArrayList<>(restTemplate.getInterceptors());
list.add(interceptor); list.add(interceptor);

@ -85,7 +85,7 @@ public class MetadataTransferAutoConfigurationTest {
.stream() .stream()
.filter(interceptor -> Objects.equals(interceptor, encodeTransferMedataRestTemplateInterceptor)) .filter(interceptor -> Objects.equals(interceptor, encodeTransferMedataRestTemplateInterceptor))
.collect(Collectors.toList()); .collect(Collectors.toList());
//EncodeTransferMedataFeignInterceptor is not added repeatedly //EncodeTransferMetadataFeignInterceptor is not added repeatedly
Assertions.assertThat(encodeTransferMedataFeignInterceptorList.size()).isEqualTo(1); Assertions.assertThat(encodeTransferMedataFeignInterceptorList.size()).isEqualTo(1);
} }
}); });

@ -15,6 +15,7 @@
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
* *
*/ */
package com.tencent.cloud.polaris.config; package com.tencent.cloud.polaris.config;
import com.tencent.cloud.polaris.config.adapter.AffectedConfigurationPropertiesRebinder; import com.tencent.cloud.polaris.config.adapter.AffectedConfigurationPropertiesRebinder;

@ -62,8 +62,10 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
// load spring boot default config files // load spring boot default config files
String[] activeProfiles = environment.getActiveProfiles(); String[] activeProfiles = environment.getActiveProfiles();
String[] defaultProfiles = environment.getDefaultProfiles();
String serviceName = environment.getProperty("spring.application.name"); String serviceName = environment.getProperty("spring.application.name");
polarisConfigFilePuller.initInternalConfigFiles(compositePropertySource, activeProfiles, serviceName); polarisConfigFilePuller.initInternalConfigFiles(
compositePropertySource, activeProfiles, defaultProfiles, serviceName);
// load custom config files // load custom config files
List<ConfigFileGroup> configFileGroups = polarisConfigProperties.getGroups(); List<ConfigFileGroup> configFileGroups = polarisConfigProperties.getGroups();

@ -17,6 +17,8 @@
package com.tencent.cloud.polaris.config.adapter; package com.tencent.cloud.polaris.config.adapter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -30,6 +32,7 @@ import com.tencent.polaris.configuration.api.core.ConfigFileMetadata;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.api.core.ConfigKVFile; import com.tencent.polaris.configuration.api.core.ConfigKVFile;
import com.tencent.polaris.configuration.client.internal.DefaultConfigFileMetadata; import com.tencent.polaris.configuration.client.internal.DefaultConfigFileMetadata;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -55,6 +58,24 @@ public final class PolarisConfigFilePuller {
private PolarisConfigFilePuller() { private PolarisConfigFilePuller() {
} }
/**
* Factory method to create PolarisConfigFilePuller for
* {@link PolarisConfigDataLoader},{@link PolarisConfigFileLocator}.
*
* @param polarisContextProperties polarisContextProperties
* @param configFileService configFileService
* @param polarisPropertySourceManager polarisPropertySourceManager
* @return PolarisConfigFilePuller instance
*/
public static PolarisConfigFilePuller get(PolarisContextProperties polarisContextProperties, ConfigFileService configFileService,
PolarisPropertySourceManager polarisPropertySourceManager) {
PolarisConfigFilePuller puller = new PolarisConfigFilePuller();
puller.polarisContextProperties = polarisContextProperties;
puller.configFileService = configFileService;
puller.polarisPropertySourceManager = polarisPropertySourceManager;
return puller;
}
/** /**
* InitInternalConfigFiles for {@link PolarisConfigDataLoader}. * InitInternalConfigFiles for {@link PolarisConfigDataLoader}.
* *
@ -62,8 +83,9 @@ public final class PolarisConfigFilePuller {
* @param activeProfiles activeProfiles * @param activeProfiles activeProfiles
* @param serviceName serviceName * @param serviceName serviceName
*/ */
public void initInternalConfigFiles(CompositePropertySource compositePropertySource, String[] activeProfiles, String serviceName) { public void initInternalConfigFiles(CompositePropertySource compositePropertySource, String[] activeProfiles,
List<ConfigFileMetadata> internalConfigFiles = getInternalConfigFiles(activeProfiles, serviceName); String[] defaultProfiles, String serviceName) {
List<ConfigFileMetadata> internalConfigFiles = getInternalConfigFiles(activeProfiles, defaultProfiles, serviceName);
for (ConfigFileMetadata configFile : internalConfigFiles) { for (ConfigFileMetadata configFile : internalConfigFiles) {
PolarisPropertySource polarisPropertySource = loadPolarisPropertySource( PolarisPropertySource polarisPropertySource = loadPolarisPropertySource(
configFile.getNamespace(), configFile.getFileGroup(), configFile.getFileName()); configFile.getNamespace(), configFile.getFileGroup(), configFile.getFileName());
@ -137,59 +159,60 @@ public final class PolarisConfigFilePuller {
return new PolarisPropertySource(namespace, group, fileName, configKVFile, map); return new PolarisPropertySource(namespace, group, fileName, configKVFile, map);
} }
private List<ConfigFileMetadata> getInternalConfigFiles(
private List<ConfigFileMetadata> getInternalConfigFiles(String[] activeProfiles, String serviceName) { String[] activeProfiles, String[] defaultProfiles, String serviceName) {
String namespace = polarisContextProperties.getNamespace(); String namespace = polarisContextProperties.getNamespace();
if (StringUtils.hasText(polarisContextProperties.getService())) { if (StringUtils.hasText(polarisContextProperties.getService())) {
serviceName = polarisContextProperties.getService(); serviceName = polarisContextProperties.getService();
} }
// priority: application-${profile} > application > boostrap-${profile} > boostrap // priority: application-${profile} > application > boostrap-${profile} > boostrap
return getInternalConfigFiles(activeProfiles, namespace, serviceName); return getInternalConfigFiles(activeProfiles, defaultProfiles, namespace, serviceName);
}
private List<ConfigFileMetadata> getInternalConfigFiles(
String[] activeProfiles, String[] defaultProfiles, String namespace, String serviceName) {
List<String> profileList = new ArrayList<>();
if (ArrayUtils.isNotEmpty(activeProfiles)) {
profileList.addAll(Arrays.asList(activeProfiles));
}
else if (ArrayUtils.isNotEmpty(defaultProfiles)) {
profileList.addAll(Arrays.asList(defaultProfiles));
} }
private List<ConfigFileMetadata> getInternalConfigFiles(String[] activeProfiles, String namespace, String serviceName) {
List<ConfigFileMetadata> internalConfigFiles = new LinkedList<>(); List<ConfigFileMetadata> internalConfigFiles = new LinkedList<>();
for (String activeProfile : activeProfiles) { // build application config files
if (!StringUtils.hasText(activeProfile)) { buildInternalApplicationConfigFiles(internalConfigFiles, namespace, serviceName, profileList);
// build bootstrap config files
buildInternalBootstrapConfigFiles(internalConfigFiles, namespace, serviceName, profileList);
return internalConfigFiles;
}
private void buildInternalApplicationConfigFiles(
List<ConfigFileMetadata> internalConfigFiles, String namespace, String serviceName, List<String> profiles) {
for (String profile : profiles) {
if (!StringUtils.hasText(profile)) {
continue; continue;
} }
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application-" + activeProfile + ".properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application-" + profile + ".properties"));
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application-" + activeProfile + ".yml")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application-" + profile + ".yml"));
} }
// build default config properties files.
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.properties"));
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.yml")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.yml"));
}
for (String activeProfile : activeProfiles) { private void buildInternalBootstrapConfigFiles(
if (!StringUtils.hasText(activeProfile)) { List<ConfigFileMetadata> internalConfigFiles, String namespace, String serviceName, List<String> profiles) {
for (String profile : profiles) {
if (!StringUtils.hasText(profile)) {
continue; continue;
} }
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap-" + profile + ".properties"));
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap-" + activeProfile + ".properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap-" + profile + ".yml"));
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap-" + activeProfile + ".yml"));
} }
// build default config properties files.
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap.properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap.properties"));
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap.yml")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap.yml"));
return internalConfigFiles;
}
/**
* Factory method to create PolarisConfigFilePuller for
* {@link PolarisConfigDataLoader},{@link PolarisConfigFileLocator}.
*
* @param polarisContextProperties polarisContextProperties
* @param configFileService configFileService
* @param polarisPropertySourceManager polarisPropertySourceManager
* @return PolarisConfigFilePuller instance
*/
public static PolarisConfigFilePuller get(PolarisContextProperties polarisContextProperties, ConfigFileService configFileService,
PolarisPropertySourceManager polarisPropertySourceManager) {
PolarisConfigFilePuller puller = new PolarisConfigFilePuller();
puller.polarisContextProperties = polarisContextProperties;
puller.configFileService = configFileService;
puller.polarisPropertySourceManager = polarisPropertySourceManager;
return puller;
} }
} }

@ -33,7 +33,9 @@ public interface PolarisConfigPropertyRefresher {
* *
* @param changedKey changedKey * @param changedKey changedKey
*/ */
void refreshSpringValue(String changedKey); default void refreshSpringValue(String changedKey) {
// do nothing,all config will be refreshed by contextRefresher.refresh
}
/** /**
* refresh @ConfigurationProperties beans. * refresh @ConfigurationProperties beans.

@ -47,7 +47,6 @@ public class ReflectRefreshTypeCondition extends SpringBootCondition {
if (refreshType == DEFAULT_REFRESH_TYPE) { if (refreshType == DEFAULT_REFRESH_TYPE) {
return ConditionOutcome.noMatch("no matched"); return ConditionOutcome.noMatch("no matched");
} }
return ConditionOutcome.match("matched"); return ConditionOutcome.match("matched");
} }
} }

@ -56,18 +56,13 @@ import static org.springframework.boot.context.config.ConfigData.Option.PROFILE_
*/ */
public class PolarisConfigDataLoader implements ConfigDataLoader<PolarisConfigDataResource> { public class PolarisConfigDataLoader implements ConfigDataLoader<PolarisConfigDataResource> {
static final AtomicBoolean INTERNAL_CONFIG_FILES_LOADED = new AtomicBoolean(false);
static final AtomicBoolean CUSTOM_POLARIS_CONFIG_FILE_LOADED = new AtomicBoolean(false);
private static final String POLARIS_CONFIG_PROPERTY_SOURCE_NAME = "polaris-config"; private static final String POLARIS_CONFIG_PROPERTY_SOURCE_NAME = "polaris-config";
private final Log log; private final Log log;
private ConfigFileService configFileService; private ConfigFileService configFileService;
private PolarisConfigFilePuller puller; private PolarisConfigFilePuller puller;
static final AtomicBoolean INTERNAL_CONFIG_FILES_LOADED = new AtomicBoolean(false);
static final AtomicBoolean CUSTOM_POLARIS_CONFIG_FILE_LOADED = new AtomicBoolean(false);
public PolarisConfigDataLoader(DeferredLogFactory logFactory) { public PolarisConfigDataLoader(DeferredLogFactory logFactory) {
this.log = logFactory.getLog(getClass()); this.log = logFactory.getLog(getClass());
} }
@ -107,9 +102,10 @@ public class PolarisConfigDataLoader implements ConfigDataLoader<PolarisConfigDa
Profiles profiles = resource.getProfiles(); Profiles profiles = resource.getProfiles();
if (INTERNAL_CONFIG_FILES_LOADED.compareAndSet(false, true)) { if (INTERNAL_CONFIG_FILES_LOADED.compareAndSet(false, true)) {
log.info("loading internal config files"); log.info("loading internal config files");
List<String> profilesActive = profiles.getActive(); String[] activeProfiles = profiles.getActive().toArray(new String[] {});
String[] activeProfiles = profilesActive.toArray(new String[]{}); String[] defaultProfiles = profiles.getDefault().toArray(new String[] {});
this.puller.initInternalConfigFiles(compositePropertySource, activeProfiles, resource.getServiceName()); this.puller.initInternalConfigFiles(
compositePropertySource, activeProfiles, defaultProfiles, resource.getServiceName());
} }
PolarisConfigProperties polarisConfigProperties = resource.getPolarisConfigProperties(); PolarisConfigProperties polarisConfigProperties = resource.getPolarisConfigProperties();

@ -144,7 +144,8 @@ public class PolarisConfigDataLocationResolver implements
// destroy earlier Polaris sdkContext // destroy earlier Polaris sdkContext
event.getBootstrapContext().get(SDKContext.class).destroy(); event.getBootstrapContext().get(SDKContext.class).destroy();
// register PolarisPropertySourceManager to context // register PolarisPropertySourceManager to context
PolarisPropertySourceManager polarisPropertySourceManager = event.getBootstrapContext().get(PolarisPropertySourceManager.class); PolarisPropertySourceManager polarisPropertySourceManager = event.getBootstrapContext()
.get(PolarisPropertySourceManager.class);
event.getApplicationContext().getBeanFactory().registerSingleton( event.getApplicationContext().getBeanFactory().registerSingleton(
"polarisPropertySourceManager", polarisPropertySourceManager); "polarisPropertySourceManager", polarisPropertySourceManager);
} }
@ -270,8 +271,7 @@ public class PolarisConfigDataLocationResolver implements
PolarisContextProperties polarisContextProperties) { PolarisContextProperties polarisContextProperties) {
// add ModifyAddress and ConfigurationModifier to load SDKContext // add ModifyAddress and ConfigurationModifier to load SDKContext
List<PolarisConfigModifier> modifierList = new ArrayList<>(); List<PolarisConfigModifier> modifierList = new ArrayList<>();
ModifyAddress modifyAddress = new ModifyAddress(); ModifyAddress modifyAddress = new ModifyAddress(polarisContextProperties);
modifyAddress.setProperties(polarisContextProperties);
ConfigurationModifier configurationModifier = new ConfigurationModifier(polarisConfigProperties, ConfigurationModifier configurationModifier = new ConfigurationModifier(polarisConfigProperties,
polarisContextProperties); polarisContextProperties);

@ -16,7 +16,6 @@
* *
*/ */
package com.tencent.cloud.polaris.config.enums; package com.tencent.cloud.polaris.config.enums;
import org.springframework.boot.context.properties.ConfigurationPropertiesBean; import org.springframework.boot.context.properties.ConfigurationPropertiesBean;

@ -15,6 +15,7 @@
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
* *
*/ */
package com.tencent.cloud.polaris.config.enums; package com.tencent.cloud.polaris.config.enums;
/** /**

@ -1,3 +1,20 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.config.spring.annotation; package com.tencent.cloud.polaris.config.spring.annotation;
import java.lang.reflect.Field; import java.lang.reflect.Field;

@ -1,3 +1,20 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.config.spring.annotation; package com.tencent.cloud.polaris.config.spring.annotation;
import java.beans.PropertyDescriptor; import java.beans.PropertyDescriptor;
@ -60,7 +77,7 @@ public class SpringValueProcessor extends PolarisProcessor implements BeanFactor
} }
@Override @Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) public void postProcessBeanFactory(@NonNull ConfigurableListableBeanFactory beanFactory)
throws BeansException { throws BeansException {
if (polarisConfigProperties.isAutoRefresh() && beanFactory instanceof BeanDefinitionRegistry) { if (polarisConfigProperties.isAutoRefresh() && beanFactory instanceof BeanDefinitionRegistry) {
beanName2SpringValueDefinitions = SpringValueDefinitionProcessor beanName2SpringValueDefinitions = SpringValueDefinitionProcessor
@ -120,11 +137,11 @@ public class SpringValueProcessor extends PolarisProcessor implements BeanFactor
SpringValue springValue; SpringValue springValue;
if (member instanceof Field) { if (member instanceof Field) {
Field field = (Field) member; Field field = (Field) member;
springValue = new SpringValue(key, value.value(), bean, beanName, field, false); springValue = new SpringValue(key, value.value(), bean, beanName, field);
} }
else if (member instanceof Method) { else if (member instanceof Method) {
Method method = (Method) member; Method method = (Method) member;
springValue = new SpringValue(key, value.value(), bean, beanName, method, false); springValue = new SpringValue(key, value.value(), bean, beanName, method);
} }
else { else {
LOGGER.error("Polaris @Value annotation currently only support to be used on methods and fields, " LOGGER.error("Polaris @Value annotation currently only support to be used on methods and fields, "
@ -137,25 +154,25 @@ public class SpringValueProcessor extends PolarisProcessor implements BeanFactor
} }
private void processBeanPropertyValues(Object bean, String beanName) { private void processBeanPropertyValues(Object bean, String beanName) {
Collection<SpringValueDefinition> propertySpringValues = beanName2SpringValueDefinitions Collection<SpringValueDefinition> propertySpringValues = beanName2SpringValueDefinitions.get(beanName);
.get(beanName); if (propertySpringValues.isEmpty()) {
if (propertySpringValues == null || propertySpringValues.isEmpty()) {
return; return;
} }
for (SpringValueDefinition definition : propertySpringValues) { for (SpringValueDefinition definition : propertySpringValues) {
try { try {
PropertyDescriptor pd = BeanUtils PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(bean.getClass(), definition.getPropertyName());
.getPropertyDescriptor(bean.getClass(), definition.getPropertyName()); if (pd != null) {
Method method = pd.getWriteMethod(); Method method = pd.getWriteMethod();
if (method == null) { if (method == null) {
continue; continue;
} }
SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(), SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(),
bean, beanName, method, false); bean, beanName, method);
springValueRegistry.register(beanFactory, definition.getKey(), springValue); springValueRegistry.register(beanFactory, definition.getKey(), springValue);
LOGGER.debug("Monitoring {}", springValue); LOGGER.debug("Monitoring {}", springValue);
} }
}
catch (Throwable ex) { catch (Throwable ex) {
LOGGER.error("Failed to enable auto update feature for {}.{}", bean.getClass(), LOGGER.error("Failed to enable auto update feature for {}.{}", bean.getClass(),
definition.getPropertyName()); definition.getPropertyName());
@ -167,7 +184,7 @@ public class SpringValueProcessor extends PolarisProcessor implements BeanFactor
} }
@Override @Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory; this.beanFactory = beanFactory;
} }
} }

@ -21,7 +21,6 @@ import java.lang.ref.WeakReference;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.springframework.core.MethodParameter; import org.springframework.core.MethodParameter;
@ -37,30 +36,24 @@ import org.springframework.core.MethodParameter;
*/ */
public class SpringValue { public class SpringValue {
private MethodParameter methodParameter;
private Field field;
private final WeakReference<Object> beanRef; private final WeakReference<Object> beanRef;
private final String beanName; private final String beanName;
private final String key; private final String key;
private final String placeholder; private final String placeholder;
private final Class<?> targetType; private final Class<?> targetType;
private Type genericType; private MethodParameter methodParameter;
private final boolean isJson; private Field field;
public SpringValue(String key, String placeholder, Object bean, String beanName, Field field, boolean isJson) { public SpringValue(String key, String placeholder, Object bean, String beanName, Field field) {
this.beanRef = new WeakReference<>(bean); this.beanRef = new WeakReference<>(bean);
this.beanName = beanName; this.beanName = beanName;
this.field = field; this.field = field;
this.key = key; this.key = key;
this.placeholder = placeholder; this.placeholder = placeholder;
this.targetType = field.getType(); this.targetType = field.getType();
this.isJson = isJson;
if (isJson) {
this.genericType = field.getGenericType();
}
} }
public SpringValue(String key, String placeholder, Object bean, String beanName, Method method, boolean isJson) { public SpringValue(String key, String placeholder, Object bean, String beanName, Method method) {
this.beanRef = new WeakReference<>(bean); this.beanRef = new WeakReference<>(bean);
this.beanName = beanName; this.beanName = beanName;
this.methodParameter = new MethodParameter(method, 0); this.methodParameter = new MethodParameter(method, 0);
@ -68,10 +61,6 @@ public class SpringValue {
this.placeholder = placeholder; this.placeholder = placeholder;
Class<?>[] paramTps = method.getParameterTypes(); Class<?>[] paramTps = method.getParameterTypes();
this.targetType = paramTps[0]; this.targetType = paramTps[0];
this.isJson = isJson;
if (isJson) {
this.genericType = method.getGenericParameterTypes()[0];
}
} }
public void update(Object newVal) throws IllegalAccessException, InvocationTargetException { public void update(Object newVal) throws IllegalAccessException, InvocationTargetException {
@ -127,14 +116,6 @@ public class SpringValue {
return field; return field;
} }
public Type getGenericType() {
return genericType;
}
public boolean isJson() {
return isJson;
}
boolean isTargetBeanValid() { boolean isTargetBeanValid() {
return beanRef.get() != null; return beanRef.get() != null;
} }

@ -35,6 +35,7 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.lang.NonNull;
/** /**
* To process xml config placeholders, e.g. * To process xml config placeholders, e.g.
@ -59,34 +60,34 @@ public class SpringValueDefinitionProcessor implements BeanDefinitionRegistryPos
private final PlaceholderHelper placeholderHelper; private final PlaceholderHelper placeholderHelper;
private PolarisConfigProperties polarisConfigProperties; private final PolarisConfigProperties polarisConfigProperties;
public SpringValueDefinitionProcessor(PlaceholderHelper placeholderHelper, PolarisConfigProperties polarisConfigProperties) { public SpringValueDefinitionProcessor(PlaceholderHelper placeholderHelper, PolarisConfigProperties polarisConfigProperties) {
this.polarisConfigProperties = polarisConfigProperties; this.polarisConfigProperties = polarisConfigProperties;
this.placeholderHelper = placeholderHelper; this.placeholderHelper = placeholderHelper;
} }
public static Multimap<String, SpringValueDefinition> getBeanName2SpringValueDefinitions(BeanDefinitionRegistry registry) {
Multimap<String, SpringValueDefinition> springValueDefinitions = beanName2SpringValueDefinitions.get(registry);
if (springValueDefinitions == null) {
springValueDefinitions = LinkedListMultimap.create();
}
return springValueDefinitions;
}
@Override @Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { public void postProcessBeanDefinitionRegistry(@NonNull BeanDefinitionRegistry registry) throws BeansException {
if (polarisConfigProperties.isAutoRefresh()) { if (polarisConfigProperties.isAutoRefresh()) {
processPropertyValues(registry); processPropertyValues(registry);
} }
} }
@Override @Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { public void postProcessBeanFactory(@NonNull ConfigurableListableBeanFactory beanFactory) throws BeansException {
} }
public static Multimap<String, SpringValueDefinition> getBeanName2SpringValueDefinitions(BeanDefinitionRegistry registry) {
Multimap<String, SpringValueDefinition> springValueDefinitions = beanName2SpringValueDefinitions.get(registry);
if (springValueDefinitions == null) {
springValueDefinitions = LinkedListMultimap.create();
}
return springValueDefinitions;
}
private void processPropertyValues(BeanDefinitionRegistry beanRegistry) { private void processPropertyValues(BeanDefinitionRegistry beanRegistry) {
if (!PROPERTY_VALUES_PROCESSED_BEAN_FACTORIES.add(beanRegistry)) { if (!PROPERTY_VALUES_PROCESSED_BEAN_FACTORIES.add(beanRegistry)) {
// already initialized // already initialized

@ -94,14 +94,8 @@ public class SpringValueRegistry {
Iterator<Multimap<String, SpringValue>> iterator = registry.values().iterator(); Iterator<Multimap<String, SpringValue>> iterator = registry.values().iterator();
while (!Thread.currentThread().isInterrupted() && iterator.hasNext()) { while (!Thread.currentThread().isInterrupted() && iterator.hasNext()) {
Multimap<String, SpringValue> springValues = iterator.next(); Multimap<String, SpringValue> springValues = iterator.next();
Iterator<Map.Entry<String, SpringValue>> springValueIterator = springValues.entries().iterator();
while (springValueIterator.hasNext()) {
Map.Entry<String, SpringValue> springValue = springValueIterator.next();
if (!springValue.getValue().isTargetBeanValid()) {
// clear unused spring values // clear unused spring values
springValueIterator.remove(); springValues.entries().removeIf(springValue -> !springValue.getValue().isTargetBeanValid());
}
}
} }
} }
} }

@ -45,6 +45,9 @@ import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class PolarisConfigFilePullerTest { public class PolarisConfigFilePullerTest {
private final String testNamespace = "testNamespace";
private final String testServiceName = "testServiceName";
private final String polarisConfigPropertySourceName = "polaris-config";
@Mock @Mock
private PolarisContextProperties polarisContextProperties; private PolarisContextProperties polarisContextProperties;
@Mock @Mock
@ -52,10 +55,6 @@ public class PolarisConfigFilePullerTest {
@Mock @Mock
private PolarisPropertySourceManager polarisPropertySourceManager; private PolarisPropertySourceManager polarisPropertySourceManager;
private final String testNamespace = "testNamespace";
private final String testServiceName = "testServiceName";
private final String polarisConfigPropertySourceName = "polaris-config";
@Test @Test
public void testPullInternalConfigFiles() { public void testPullInternalConfigFiles() {
PolarisConfigFilePuller puller = PolarisConfigFilePuller.get(polarisContextProperties, configFileService, PolarisConfigFilePuller puller = PolarisConfigFilePuller.get(polarisContextProperties, configFileService,
@ -80,7 +79,7 @@ public class PolarisConfigFilePullerTest {
when(configFileService.getConfigYamlFile(testNamespace, testServiceName, "bootstrap.yml")).thenReturn(emptyConfigFile); when(configFileService.getConfigYamlFile(testNamespace, testServiceName, "bootstrap.yml")).thenReturn(emptyConfigFile);
CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName);
puller.initInternalConfigFiles(compositePropertySource, new String[]{}, testServiceName); puller.initInternalConfigFiles(compositePropertySource, new String[] {}, new String[] {}, testServiceName);
Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); Assert.assertEquals("v1", compositePropertySource.getProperty("k1"));
Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); Assert.assertEquals("v2", compositePropertySource.getProperty("k2"));
@ -123,7 +122,7 @@ public class PolarisConfigFilePullerTest {
active.add("dev"); active.add("dev");
String[] activeProfiles = active.toArray(new String[] {}); String[] activeProfiles = active.toArray(new String[] {});
CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName);
puller.initInternalConfigFiles(compositePropertySource, activeProfiles, testServiceName); puller.initInternalConfigFiles(compositePropertySource, activeProfiles, new String[] {}, testServiceName);
Assert.assertEquals("v11", compositePropertySource.getProperty("k1")); Assert.assertEquals("v11", compositePropertySource.getProperty("k1"));
Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); Assert.assertEquals("v2", compositePropertySource.getProperty("k2"));

@ -83,7 +83,7 @@ public class PolarisPropertiesSourceAutoRefresherTest {
MockedConfigChange mockedConfigChange = new MockedConfigChange(); MockedConfigChange mockedConfigChange = new MockedConfigChange();
mockedConfigChange.setK1("v1"); mockedConfigChange.setK1("v1");
Field field = mockedConfigChange.getClass().getDeclaredField("k1"); Field field = mockedConfigChange.getClass().getDeclaredField("k1");
SpringValue springValue = new SpringValue("v1", "placeholder", mockedConfigChange, "mockedConfigChange", field, false); SpringValue springValue = new SpringValue("v1", "placeholder", mockedConfigChange, "mockedConfigChange", field);
springValues.add(springValue); springValues.add(springValue);

@ -15,6 +15,7 @@
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
* *
*/ */
package com.tencent.cloud.polaris; package com.tencent.cloud.polaris;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

@ -14,6 +14,7 @@
* CONDITIONS OF ANY KIND, either express or implied. See the License for the * CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*/ */
package com.tencent.cloud.polaris.discovery.refresh; package com.tencent.cloud.polaris.discovery.refresh;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;

@ -14,6 +14,7 @@
* CONDITIONS OF ANY KIND, either express or implied. See the License for the * CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*/ */
package com.tencent.cloud.polaris.discovery.refresh; package com.tencent.cloud.polaris.discovery.refresh;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;

@ -14,6 +14,7 @@
* CONDITIONS OF ANY KIND, either express or implied. See the License for the * CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*/ */
package com.tencent.cloud.polaris.discovery.refresh; package com.tencent.cloud.polaris.discovery.refresh;
import java.util.Set; import java.util.Set;

@ -123,7 +123,6 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
@Override @Override
public void deregister(Registration registration) { public void deregister(Registration registration) {
LOGGER.info("De-registering from Polaris Server now..."); LOGGER.info("De-registering from Polaris Server now...");
if (StringUtils.isEmpty(registration.getServiceId())) { if (StringUtils.isEmpty(registration.getServiceId())) {
@ -155,10 +154,12 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
@Override @Override
public void close() { public void close() {
} }
@Override @Override
public void setStatus(Registration registration, String status) { public void setStatus(Registration registration, String status) {
} }
@Override @Override

@ -31,17 +31,18 @@ public final class RateLimitConstant {
* Order of filter. * Order of filter.
*/ */
public static final int FILTER_ORDER = Ordered.HIGHEST_PRECEDENCE + 10; public static final int FILTER_ORDER = Ordered.HIGHEST_PRECEDENCE + 10;
/** /**
* Info of rate limit. * Info of rate limit.
*/ */
public static String QUOTA_LIMITED_INFO = "The request is denied by rate limit because the throttling threshold is reached"; public static String QUOTA_LIMITED_INFO = "The request is denied by rate limit because the throttling threshold is reached";
/** /**
* The build in label method. * The build in label method.
*/ */
public static String LABEL_METHOD = "method"; public static String LABEL_METHOD = "method";
/**
* Default Private Constructor.
*/
private RateLimitConstant() { private RateLimitConstant() {
} }
} }

@ -77,7 +77,7 @@ public class PolarisRateLimitRuleEndpoint {
} }
for (RateLimitProto.Rule rule : rateLimit.getRulesList()) { for (RateLimitProto.Rule rule : rateLimit.getRulesList()) {
String ruleJson = ""; String ruleJson;
try { try {
ruleJson = JsonFormat.printer().print(rule); ruleJson = JsonFormat.printer().print(rule);
} }

@ -60,7 +60,7 @@ import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.LAB
*/ */
public class QuotaCheckReactiveFilter implements WebFilter, Ordered { public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckReactiveFilter.class); private static final Logger LOGGER = LoggerFactory.getLogger(QuotaCheckReactiveFilter.class);
private final LimitAPI limitAPI; private final LimitAPI limitAPI;
@ -114,14 +114,14 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
} }
// Unirate // Unirate
if (quotaResponse.getCode() == QuotaResultCode.QuotaResultOk && quotaResponse.getWaitMs() > 0) { if (quotaResponse.getCode() == QuotaResultCode.QuotaResultOk && quotaResponse.getWaitMs() > 0) {
LOG.debug("The request of [{}] will waiting for {}ms.", path, quotaResponse.getWaitMs()); LOGGER.debug("The request of [{}] will waiting for {}ms.", path, quotaResponse.getWaitMs());
return Mono.delay(Duration.ofMillis(quotaResponse.getWaitMs())).flatMap(e -> chain.filter(exchange)); return Mono.delay(Duration.ofMillis(quotaResponse.getWaitMs())).flatMap(e -> chain.filter(exchange));
} }
} }
catch (Throwable t) { catch (Throwable t) {
// An exception occurs in the rate limiting API call, // An exception occurs in the rate limiting API call,
// which should not affect the call of the business process. // which should not affect the call of the business process.
LOG.error("fail to invoke getQuota, service is " + localService, t); LOGGER.error("fail to invoke getQuota, service is " + localService, t);
} }
return chain.filter(exchange); return chain.filter(exchange);
@ -153,7 +153,7 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
return labelResolver.resolve(exchange); return labelResolver.resolve(exchange);
} }
catch (Throwable e) { catch (Throwable e) {
LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e); LOGGER.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e);
} }
} }
return Maps.newHashMap(); return Maps.newHashMap();

@ -46,6 +46,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.lang.NonNull;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.LABEL_METHOD; import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.LABEL_METHOD;
@ -58,13 +59,11 @@ import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.LAB
@Order(RateLimitConstant.FILTER_ORDER) @Order(RateLimitConstant.FILTER_ORDER)
public class QuotaCheckServletFilter extends OncePerRequestFilter { public class QuotaCheckServletFilter extends OncePerRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class);
/** /**
* Default Filter Registration Bean Name Defined . * Default Filter Registration Bean Name Defined .
*/ */
public static final String QUOTA_FILTER_BEAN_NAME = "quotaFilterRegistrationBean"; public static final String QUOTA_FILTER_BEAN_NAME = "quotaFilterRegistrationBean";
private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class);
private final LimitAPI limitAPI; private final LimitAPI limitAPI;
private final PolarisRateLimiterLabelServletResolver labelResolver; private final PolarisRateLimiterLabelServletResolver labelResolver;
@ -91,7 +90,8 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter {
} }
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException { throws ServletException, IOException {
String localNamespace = MetadataContext.LOCAL_NAMESPACE; String localNamespace = MetadataContext.LOCAL_NAMESPACE;
String localService = MetadataContext.LOCAL_SERVICE; String localService = MetadataContext.LOCAL_SERVICE;

@ -14,6 +14,7 @@
* CONDITIONS OF ANY KIND, either express or implied. See the License for the * CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*/ */
package com.tencent.cloud.polaris.ratelimit.utils; package com.tencent.cloud.polaris.ratelimit.utils;
import java.util.Map; import java.util.Map;

@ -18,7 +18,6 @@
package com.tencent.cloud.polaris.router; package com.tencent.cloud.polaris.router;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;

@ -24,11 +24,15 @@ package com.tencent.cloud.common.constant;
* @author lepdou 2022-05-17 * @author lepdou 2022-05-17
*/ */
public final class RouterConstants { public final class RouterConstants {
/** /**
* the header of router label. * the header of router label.
*/ */
public static final String ROUTER_LABEL_HEADER = "internal-router-label"; public static final String ROUTER_LABEL_HEADER = "internal-router-label";
/**
* Default Private Constructor.
*/
private RouterConstants() { private RouterConstants() {
} }
} }

@ -3,6 +3,8 @@ server:
spring: spring:
application: application:
name: polaris-config-example name: polaris-config-example
profiles:
active: abc
cloud: cloud:
polaris: polaris:
address: grpc://183.47.111.80:8091 address: grpc://183.47.111.80:8091

@ -26,8 +26,6 @@ import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.factory.config.ConfigurationImpl; import com.tencent.polaris.factory.config.ConfigurationImpl;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
/** /**
* Modify polaris server address. * Modify polaris server address.
* *
@ -35,8 +33,11 @@ import org.springframework.beans.factory.annotation.Autowired;
*/ */
public class ModifyAddress implements PolarisConfigModifier { public class ModifyAddress implements PolarisConfigModifier {
@Autowired private final PolarisContextProperties properties;
private PolarisContextProperties properties;
public ModifyAddress(PolarisContextProperties properties) {
this.properties = properties;
}
@Override @Override
public void modify(ConfigurationImpl configuration) { public void modify(ConfigurationImpl configuration) {
@ -53,8 +54,4 @@ public class ModifyAddress implements PolarisConfigModifier {
public int getOrder() { public int getOrder() {
return ContextConstant.ModifierOrder.FIRST; return ContextConstant.ModifierOrder.FIRST;
} }
public void setProperties(PolarisContextProperties properties) {
this.properties = properties;
}
} }

@ -68,8 +68,8 @@ public class PolarisContextAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public ModifyAddress polarisConfigModifier() { public ModifyAddress polarisConfigModifier(PolarisContextProperties properties) {
return new ModifyAddress(); return new ModifyAddress(properties);
} }
@Bean @Bean

@ -24,6 +24,7 @@ import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener; import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType; import org.springframework.core.ResolvableType;
import org.springframework.lang.NonNull;
/** /**
* Reload of Polaris logging configuration. * Reload of Polaris logging configuration.
@ -50,7 +51,7 @@ public class PolarisLoggingApplicationListener implements GenericApplicationList
} }
@Override @Override
public void onApplicationEvent(ApplicationEvent applicationEvent) { public void onApplicationEvent(@NonNull ApplicationEvent applicationEvent) {
PolarisLogging.getInstance().loadConfiguration(); PolarisLogging.getInstance().loadConfiguration();
} }
} }

@ -52,7 +52,6 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* Test for {@link PolarisLoadBalancer}. * Test for {@link PolarisLoadBalancer}.
* *
@ -61,6 +60,8 @@ import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class PolarisLoadBalancerTest { public class PolarisLoadBalancerTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static Instance testInstance;
@Mock @Mock
private RouterAPI routerAPI; private RouterAPI routerAPI;
@Mock @Mock
@ -68,9 +69,6 @@ public class PolarisLoadBalancerTest {
@Mock @Mock
private PolarisLoadBalancerProperties loadBalancerProperties; private PolarisLoadBalancerProperties loadBalancerProperties;
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static Instance testInstance;
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class); mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);

@ -35,7 +35,7 @@ import org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLo
*/ */
public class EnhancedFeignBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { public class EnhancedFeignBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware {
private EnhancedFeignPluginRunner pluginRunner; private final EnhancedFeignPluginRunner pluginRunner;
private BeanFactory factory; private BeanFactory factory;

Loading…
Cancel
Save