Commit c853b31d by Yiming Liu

Extract thread build into ThreadFactory

parent 8563b8b9
...@@ -5,6 +5,7 @@ import com.ctrip.apollo.client.loader.ConfigLoaderManager; ...@@ -5,6 +5,7 @@ import com.ctrip.apollo.client.loader.ConfigLoaderManager;
import com.ctrip.apollo.client.model.PropertyChange; import com.ctrip.apollo.client.model.PropertyChange;
import com.ctrip.apollo.client.model.PropertySourceReloadResult; import com.ctrip.apollo.client.model.PropertySourceReloadResult;
import com.ctrip.apollo.client.util.ConfigUtil; import com.ctrip.apollo.client.util.ConfigUtil;
import com.ctrip.apollo.core.utils.ApolloThreadFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -27,8 +28,6 @@ import org.springframework.core.env.MutablePropertySources; ...@@ -27,8 +28,6 @@ import org.springframework.core.env.MutablePropertySources;
import java.util.List; import java.util.List;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
/** /**
...@@ -37,17 +36,18 @@ import java.util.concurrent.atomic.AtomicReference; ...@@ -37,17 +36,18 @@ import java.util.concurrent.atomic.AtomicReference;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class ApolloConfigManager public class ApolloConfigManager
implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, ApplicationContextAware { implements
BeanDefinitionRegistryPostProcessor,
PriorityOrdered,
ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(ApolloConfigManager.class); private static final Logger logger = LoggerFactory.getLogger(ApolloConfigManager.class);
private static AtomicReference<ApolloConfigManager> private static AtomicReference<ApolloConfigManager> singletonProtector =
singletonProtector =
new AtomicReference<ApolloConfigManager>(); new AtomicReference<ApolloConfigManager>();
private ConfigLoaderManager configLoaderManager; private ConfigLoaderManager configLoaderManager;
private ConfigurableApplicationContext applicationContext; private ConfigurableApplicationContext applicationContext;
private ConfigUtil configUtil; private ConfigUtil configUtil;
private ScheduledExecutorService executorService; private ScheduledExecutorService executorService;
private AtomicLong counter;
private RefreshScope scope; private RefreshScope scope;
public ApolloConfigManager() { public ApolloConfigManager() {
...@@ -56,32 +56,25 @@ public class ApolloConfigManager ...@@ -56,32 +56,25 @@ public class ApolloConfigManager
} }
this.configLoaderManager = ConfigLoaderFactory.getInstance().getConfigLoaderManager(); this.configLoaderManager = ConfigLoaderFactory.getInstance().getConfigLoaderManager();
this.configUtil = ConfigUtil.getInstance(); this.configUtil = ConfigUtil.getInstance();
this.counter = new AtomicLong(); executorService =
executorService = Executors.newScheduledThreadPool(1, new ThreadFactory() { Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("ConfigManager", true));
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "ApolloConfigManager-" + counter.incrementAndGet());
return thread;
}
});
} }
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (!(applicationContext instanceof ConfigurableApplicationContext)) { if (!(applicationContext instanceof ConfigurableApplicationContext)) {
throw new RuntimeException( throw new RuntimeException(String.format(
String.format( "ApplicationContext must implement ConfigurableApplicationContext, but found: %s",
"ApplicationContext must implement ConfigurableApplicationContext, but found: %s", applicationContext.getClass().getName()));
applicationContext.getClass().getName()));
} }
this.applicationContext = (ConfigurableApplicationContext) applicationContext; this.applicationContext = (ConfigurableApplicationContext) applicationContext;
this.configUtil.setApplicationContext(applicationContext); this.configUtil.setApplicationContext(applicationContext);
} }
/** /**
* This is the first method invoked, so we could prepare the property sources here. * This is the first method invoked, so we could prepare the property sources here. Specifically
* Specifically we need to finish preparing property source before PropertySourcesPlaceholderConfigurer * we need to finish preparing property source before PropertySourcesPlaceholderConfigurer so that
* so that configurations could be injected correctly * configurations could be injected correctly
*/ */
@Override @Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
...@@ -93,22 +86,16 @@ public class ApolloConfigManager ...@@ -93,22 +86,16 @@ public class ApolloConfigManager
/** /**
* Register beans needed for Apollo Config Client * Register beans needed for Apollo Config Client
* <li> * <li>- RefreshScope: used to refresh beans when configurations changes</li>
* - RefreshScope: used to refresh beans when configurations changes * <li>- PropertySourcesPlaceholderConfigurer: used to support placeholder configuration injection
* </li>
* <li>
* - PropertySourcesPlaceholderConfigurer: used to support placeholder configuration injection
* </li> * </li>
*/ */
private void registerDependentBeans(BeanDefinitionRegistry registry) { private void registerDependentBeans(BeanDefinitionRegistry registry) {
BeanDefinition BeanDefinition refreshScope =
refreshScope =
BeanDefinitionBuilder.genericBeanDefinition(RefreshScope.class).getBeanDefinition(); BeanDefinitionBuilder.genericBeanDefinition(RefreshScope.class).getBeanDefinition();
registry.registerBeanDefinition("refreshScope", refreshScope); registry.registerBeanDefinition("refreshScope", refreshScope);
BeanDefinition BeanDefinition propertySourcesPlaceholderConfigurer = BeanDefinitionBuilder
propertySourcesPlaceholderConfigurer = .genericBeanDefinition(PropertySourcesPlaceholderConfigurer.class).getBeanDefinition();
BeanDefinitionBuilder.genericBeanDefinition(PropertySourcesPlaceholderConfigurer.class)
.getBeanDefinition();
registry.registerBeanDefinition("propertySourcesPlaceholderConfigurer", registry.registerBeanDefinition("propertySourcesPlaceholderConfigurer",
propertySourcesPlaceholderConfigurer); propertySourcesPlaceholderConfigurer);
} }
...@@ -118,8 +105,7 @@ public class ApolloConfigManager ...@@ -118,8 +105,7 @@ public class ApolloConfigManager
*/ */
@Override @Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException { throws BeansException {}
}
/** /**
* Make sure this bean is called before other beans * Make sure this bean is called before other beans
...@@ -133,15 +119,14 @@ public class ApolloConfigManager ...@@ -133,15 +119,14 @@ public class ApolloConfigManager
* Initialize property sources * Initialize property sources
*/ */
void initializePropertySource() { void initializePropertySource() {
//TODO stop application from starting when config cannot be loaded? // TODO stop application from starting when config cannot be loaded?
CompositePropertySource result = this.configLoaderManager.loadPropertySource(); CompositePropertySource result = this.configLoaderManager.loadPropertySource();
updateEnvironmentPropertySource(result); updateEnvironmentPropertySource(result);
} }
private void updateEnvironmentPropertySource(CompositePropertySource currentPropertySource) { private void updateEnvironmentPropertySource(CompositePropertySource currentPropertySource) {
MutablePropertySources MutablePropertySources currentPropertySources =
currentPropertySources =
applicationContext.getEnvironment().getPropertySources(); applicationContext.getEnvironment().getPropertySources();
if (currentPropertySources.contains(currentPropertySource.getName())) { if (currentPropertySources.contains(currentPropertySource.getName())) {
currentPropertySources.replace(currentPropertySource.getName(), currentPropertySource); currentPropertySources.replace(currentPropertySource.getName(), currentPropertySource);
...@@ -151,17 +136,16 @@ public class ApolloConfigManager ...@@ -151,17 +136,16 @@ public class ApolloConfigManager
} }
void schedulePeriodicRefresh() { void schedulePeriodicRefresh() {
executorService.scheduleAtFixedRate( executorService.scheduleAtFixedRate(new Runnable() {
new Runnable() { @Override
@Override public void run() {
public void run() { try {
try { updatePropertySource();
updatePropertySource(); } catch (Throwable ex) {
} catch (Throwable ex) { logger.error("Refreshing config failed", ex);
logger.error("Refreshing config failed", ex); }
} }
} }, configUtil.getRefreshInterval(), configUtil.getRefreshInterval(),
}, configUtil.getRefreshInterval(), configUtil.getRefreshInterval(),
configUtil.getRefreshTimeUnit()); configUtil.getRefreshTimeUnit());
} }
......
...@@ -10,6 +10,7 @@ import com.ctrip.apollo.client.model.PropertyChange; ...@@ -10,6 +10,7 @@ import com.ctrip.apollo.client.model.PropertyChange;
import com.ctrip.apollo.client.model.PropertySourceReloadResult; import com.ctrip.apollo.client.model.PropertySourceReloadResult;
import com.ctrip.apollo.client.util.ConfigUtil; import com.ctrip.apollo.client.util.ConfigUtil;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import com.ctrip.apollo.core.utils.ApolloThreadFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -26,8 +27,6 @@ import java.util.concurrent.ExecutionException; ...@@ -26,8 +27,6 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
...@@ -38,7 +37,6 @@ public class ConfigLoaderManager { ...@@ -38,7 +37,6 @@ public class ConfigLoaderManager {
private ConfigLoader configLoader; private ConfigLoader configLoader;
private ConfigUtil configUtil; private ConfigUtil configUtil;
private final ExecutorService executorService; private final ExecutorService executorService;
private final AtomicLong counter;
private Map<ApolloRegistry, ApolloConfig> currentApolloRegistryConfigCache; private Map<ApolloRegistry, ApolloConfig> currentApolloRegistryConfigCache;
private Map<ApolloRegistry, ApolloConfig> previousApolloRegistryConfigCache; private Map<ApolloRegistry, ApolloConfig> previousApolloRegistryConfigCache;
private List<ApolloRegistry> apolloRegistries; private List<ApolloRegistry> apolloRegistries;
...@@ -46,14 +44,8 @@ public class ConfigLoaderManager { ...@@ -46,14 +44,8 @@ public class ConfigLoaderManager {
public ConfigLoaderManager(ConfigLoader configLoader, ConfigUtil configUtil) { public ConfigLoaderManager(ConfigLoader configLoader, ConfigUtil configUtil) {
this.configLoader = configLoader; this.configLoader = configLoader;
this.configUtil = configUtil; this.configUtil = configUtil;
this.counter = new AtomicLong(); this.executorService =
this.executorService = Executors.newFixedThreadPool(5, new ThreadFactory() { Executors.newFixedThreadPool(5, ApolloThreadFactory.create("ConfigLoaderManager", true));
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "ConfigLoaderManager-" + counter.incrementAndGet());
return thread;
}
});
this.currentApolloRegistryConfigCache = Maps.newConcurrentMap(); this.currentApolloRegistryConfigCache = Maps.newConcurrentMap();
} }
...@@ -69,17 +61,15 @@ public class ConfigLoaderManager { ...@@ -69,17 +61,15 @@ public class ConfigLoaderManager {
public PropertySourceReloadResult reloadPropertySource() { public PropertySourceReloadResult reloadPropertySource() {
CompositePropertySource composite = loadPropertySourceWithApolloRegistries(apolloRegistries); CompositePropertySource composite = loadPropertySourceWithApolloRegistries(apolloRegistries);
List<ApolloConfig> List<ApolloConfig> previous =
previous =
Lists.newArrayList(this.previousApolloRegistryConfigCache.values()); Lists.newArrayList(this.previousApolloRegistryConfigCache.values());
List<ApolloConfig> current = Lists.newArrayList(this.currentApolloRegistryConfigCache.values()); List<ApolloConfig> current = Lists.newArrayList(this.currentApolloRegistryConfigCache.values());
return new PropertySourceReloadResult(composite, calcPropertyChanges(previous, current)); return new PropertySourceReloadResult(composite, calcPropertyChanges(previous, current));
} }
/** /**
* Load property source with apollo registries provided * Load property source with apollo registries provided Should not be invoked in parallel since
* Should not be invoked in parallel since there are some operations like create/destroy cache, * there are some operations like create/destroy cache, writing to files etc.
* writing to files etc.
*/ */
private synchronized CompositePropertySource loadPropertySourceWithApolloRegistries( private synchronized CompositePropertySource loadPropertySourceWithApolloRegistries(
List<ApolloRegistry> apolloRegistries) { List<ApolloRegistry> apolloRegistries) {
...@@ -104,7 +94,7 @@ public class ConfigLoaderManager { ...@@ -104,7 +94,7 @@ public class ConfigLoaderManager {
} }
List<PropertyChange> calcPropertyChanges(List<ApolloConfig> previous, List<PropertyChange> calcPropertyChanges(List<ApolloConfig> previous,
List<ApolloConfig> current) { List<ApolloConfig> current) {
Map<String, Object> previousMap = collectConfigurations(previous); Map<String, Object> previousMap = collectConfigurations(previous);
Map<String, Object> currentMap = collectConfigurations(current); Map<String, Object> currentMap = collectConfigurations(current);
...@@ -130,9 +120,8 @@ public class ConfigLoaderManager { ...@@ -130,9 +120,8 @@ public class ConfigLoaderManager {
if (previousMap.get(commonKey).equals(currentMap.get(commonKey))) { if (previousMap.get(commonKey).equals(currentMap.get(commonKey))) {
continue; continue;
} }
changes.add( changes.add(new PropertyChange(commonKey, previousMap.get(commonKey),
new PropertyChange(commonKey, previousMap.get(commonKey), currentMap.get(commonKey), currentMap.get(commonKey), PropertyChangeType.MODIFIED));
PropertyChangeType.MODIFIED));
} }
return changes; return changes;
...@@ -173,8 +162,7 @@ public class ConfigLoaderManager { ...@@ -173,8 +162,7 @@ public class ConfigLoaderManager {
} }
ApolloConfig loadSingleApolloConfig(ApolloRegistry apolloRegistry) { ApolloConfig loadSingleApolloConfig(ApolloRegistry apolloRegistry) {
ApolloConfig ApolloConfig result =
result =
configLoader.loadApolloConfig(apolloRegistry, getPreviousApolloConfig(apolloRegistry)); configLoader.loadApolloConfig(apolloRegistry, getPreviousApolloConfig(apolloRegistry));
if (result == null) { if (result == null) {
logger.error("Loaded config null..."); logger.error("Loaded config null...");
......
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