Commit e54448ed authored by liaozan's avatar liaozan 🏀

Refactor

parent 5c3e0dd9
package com.schbrain.common.util;
import cn.hutool.extra.spring.SpringUtil;
import com.schbrain.common.exception.BaseException;
import org.springframework.core.env.Environment;
import org.springframework.core.env.EnvironmentCapable;
import java.util.Optional;
/**
* @author liaozan
......@@ -8,8 +13,15 @@ import org.springframework.core.env.Environment;
*/
public class ApplicationName {
public static String get() {
return Optional.ofNullable(SpringUtil.getApplicationContext())
.map(EnvironmentCapable::getEnvironment)
.map(ApplicationName::get)
.orElseThrow(() -> new BaseException("Could not get application name"));
}
public static String get(Environment environment) {
return environment.getRequiredProperty("spring.application.name");
}
}
}
\ No newline at end of file
......@@ -6,14 +6,14 @@ import java.util.LinkedHashMap;
import java.util.Map;
/**
* mark class to ensure property order
* ordered property source
*
* @author liaozan
* @since 2021/12/6
*/
public class SchbrainMapPropertySource extends MapPropertySource {
public class OrderedMapPropertySource extends MapPropertySource {
public SchbrainMapPropertySource(String name, Map<String, String> source) {
public OrderedMapPropertySource(String name, Map<String, String> source) {
super(name, new LinkedHashMap<>(source));
}
......
......@@ -6,7 +6,6 @@ import com.schbrain.common.exception.BaseException;
import com.schbrain.common.util.ApplicationName;
import org.redisson.api.*;
import org.springframework.beans.BeansException;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import java.util.List;
......@@ -19,7 +18,7 @@ import java.util.concurrent.TimeUnit;
*/
public class DelayedQueueUtils {
private static final String APPLICATION_NAME = ApplicationName.get(SpringUtil.getBean(Environment.class));
private static final String APPLICATION_NAME = ApplicationName.get();
private static final ConcurrentHashMap<String, RBlockingQueue<?>> blockingQueueCache = new ConcurrentHashMap<>();
......
......@@ -8,7 +8,6 @@ import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeansException;
import org.springframework.core.env.Environment;
import java.time.Duration;
import java.util.concurrent.Callable;
......@@ -21,7 +20,7 @@ import java.util.concurrent.TimeUnit;
@Slf4j
public class RedisLockUtils {
private static final String APPLICATION_NAME = ApplicationName.get(SpringUtil.getBean(Environment.class));
private static final String APPLICATION_NAME = ApplicationName.get();
private static RedissonClient CLIENT;
......
......@@ -24,8 +24,8 @@ public class BaseException extends RuntimeException {
this(message, null);
}
public BaseException(String message, Throwable throwable) {
this(message, throwable, SERVER_ERROR, ALERT);
public BaseException(String message, Throwable cause) {
this(message, cause, SERVER_ERROR, ALERT);
}
public BaseException(String message, int code, int action) {
......
......@@ -242,7 +242,15 @@ public class DefaultGlobalExceptionHandler implements GlobalExceptionHandler {
protected void logError(Throwable throwable) {
String exMsg = ExceptionUtil.getMessage(throwable);
if (hasCause(throwable)) {
exMsg = exMsg + ", " + ExceptionUtil.getRootCauseMessage(throwable);
throwable = ExceptionUtil.getRootCause(throwable);
}
log.error(exMsg, throwable);
}
private boolean hasCause(Throwable throwable) {
return throwable.getCause() != null;
}
}
\ No newline at end of file
......@@ -13,7 +13,6 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
......@@ -39,8 +38,8 @@ public class RateLimitAspect {
private final StringRedisTemplate stringRedisTemplate;
public RateLimitAspect(Environment environment, StringRedisTemplate stringRedisTemplate) {
this.keyPrefix = ApplicationName.get(environment);
public RateLimitAspect(StringRedisTemplate stringRedisTemplate) {
this.keyPrefix = ApplicationName.get();
this.stringRedisTemplate = stringRedisTemplate;
}
......
......@@ -3,7 +3,7 @@ package com.schbrain.framework.autoconfigure.apollo;
import com.ctrip.framework.foundation.Foundation;
import com.schbrain.common.util.ApplicationName;
import com.schbrain.common.util.EnvUtils;
import com.schbrain.framework.support.spring.EnvironmentPostProcessorLoggerAwareAdapter;
import com.schbrain.framework.support.spring.LoggerAwareEnvironmentPostProcessor;
import com.schbrain.framework.support.spring.defaults.DefaultPropertiesEnvironmentPostProcessor;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
......@@ -23,7 +23,7 @@ import static com.ctrip.framework.apollo.spring.config.PropertySourcesConstants.
* @author liaozan
* @since 2021/11/6
*/
public class ApolloConfigurationInitializer extends EnvironmentPostProcessorLoggerAwareAdapter implements Ordered {
public class ApolloConfigurationInitializerEnvironmentPostProcessor extends LoggerAwareEnvironmentPostProcessor implements Ordered {
/**
* load properties after set the default properties
......@@ -36,9 +36,9 @@ public class ApolloConfigurationInitializer extends EnvironmentPostProcessorLogg
private final ConfigurablePropertiesLoader configurablePropertiesLoader;
public ApolloConfigurationInitializer(DeferredLogFactory deferredLogFactory, ConfigurableBootstrapContext bootstrapContext) {
public ApolloConfigurationInitializerEnvironmentPostProcessor(DeferredLogFactory deferredLogFactory, ConfigurableBootstrapContext bootstrapContext) {
super(deferredLogFactory, bootstrapContext);
this.configurablePropertiesLoader = new ConfigurablePropertiesLoader(getDeferredLogFactory());
this.configurablePropertiesLoader = new ConfigurablePropertiesLoader(deferredLogFactory);
}
@Override
......@@ -63,26 +63,26 @@ public class ApolloConfigurationInitializer extends EnvironmentPostProcessorLogg
private void setRequiredProperty(ConfigurableEnvironment environment) {
String appId = getAppId(environment);
saveProperty(APP_ID, appId);
setPropertyToSystem(APP_ID, appId);
String env = getEnv(environment);
saveProperty(ENV_KEY, env);
setPropertyToSystem(ENV_KEY, env);
String apolloUrl = getApolloUrl(environment, env);
saveProperty(APOLLO_META, apolloUrl);
String metaServerUrl = getApolloMetaServerUrl(environment, env);
setPropertyToSystem(APOLLO_META, metaServerUrl);
saveProperty(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, true);
saveProperty(APOLLO_BOOTSTRAP_ENABLED, true);
saveProperty(APOLLO_CACHE_FILE_ENABLE, true);
saveProperty(APOLLO_PROPERTY_ORDER_ENABLE, true);
setPropertyToSystem(APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, true);
setPropertyToSystem(APOLLO_BOOTSTRAP_ENABLED, true);
setPropertyToSystem(APOLLO_CACHE_FILE_ENABLE, true);
setPropertyToSystem(APOLLO_PROPERTY_ORDER_ENABLE, true);
// DO NOT set to true. After caching the property name, SpringBoot may not be able to bind the properties
saveProperty(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, false);
saveProperty(APOLLO_OVERRIDE_SYSTEM_PROPERTIES, false);
setPropertyToSystem(APOLLO_PROPERTY_NAMES_CACHE_ENABLE, false);
setPropertyToSystem(APOLLO_OVERRIDE_SYSTEM_PROPERTIES, false);
printProperties();
}
private void saveProperty(String key, Object value) {
private void setPropertyToSystem(String key, Object value) {
INIT_PROPERTIES.put(key, value);
System.setProperty(key, value.toString());
}
......@@ -97,7 +97,12 @@ public class ApolloConfigurationInitializer extends EnvironmentPostProcessorLogg
System.out.println(message);
}
private String getApolloUrl(ConfigurableEnvironment environment, String env) {
/**
* get apollo meta server url
*
* @see com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider#getProperty(String, String)
*/
private String getApolloMetaServerUrl(ConfigurableEnvironment environment, String env) {
String fallbackKey = env + ".meta";
// {env}.meta
......@@ -125,6 +130,11 @@ public class ApolloConfigurationInitializer extends EnvironmentPostProcessorLogg
return Foundation.getProperty(fallbackKey, null);
}
/**
* get env
*
* @see #getApolloMetaServerUrl(org.springframework.core.env.ConfigurableEnvironment, String)
*/
private String getEnv(ConfigurableEnvironment environment) {
String profile = EnvUtils.getProfile(environment);
if (profile == null) {
......@@ -133,6 +143,12 @@ public class ApolloConfigurationInitializer extends EnvironmentPostProcessorLogg
return profile;
}
/**
* get AppId
*
* @see com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider#initAppId()
*/
@SuppressWarnings("JavadocReference")
private String getAppId(ConfigurableEnvironment environment) {
String appId;
if (environment.containsProperty(APP_ID)) {
......
......@@ -3,7 +3,7 @@ package com.schbrain.framework.autoconfigure.apollo;
import cn.hutool.core.thread.GlobalThreadPool;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.schbrain.common.util.properties.SchbrainMapPropertySource;
import com.schbrain.common.util.properties.OrderedMapPropertySource;
import com.schbrain.common.util.support.ConfigurableProperties;
import com.schbrain.framework.autoconfigure.apollo.listener.PropertiesPreparedEvent;
import com.schbrain.framework.autoconfigure.apollo.listener.PropertiesPreparedEventListener;
......@@ -66,7 +66,7 @@ class ConfigurablePropertiesLoader {
configurableProperties.forEach(properties -> {
String namespace = properties.getDefaultNamespace();
Config config = ConfigService.getConfig(namespace);
SchbrainMapPropertySource propertySource = ConfigUtils.toPropertySource(namespace, config);
OrderedMapPropertySource propertySource = ConfigUtils.toPropertySource(namespace, config);
if (propertySource == null) {
log.warn("No configuration properties loaded under namespace: " + namespace);
return;
......
package com.schbrain.framework.autoconfigure.apollo.listener;
import com.schbrain.common.util.properties.SchbrainMapPropertySource;
import com.schbrain.common.util.properties.OrderedMapPropertySource;
import com.schbrain.common.util.support.ConfigurableProperties;
import lombok.Getter;
import org.springframework.boot.SpringApplication;
......@@ -21,13 +21,13 @@ public class PropertiesPreparedEvent extends ApplicationEvent {
private final DeferredLogFactory deferredLogFactory;
private final SchbrainMapPropertySource propertySource;
private final OrderedMapPropertySource propertySource;
private final SpringApplication application;
public PropertiesPreparedEvent(ConfigurableEnvironment environment,
DeferredLogFactory deferredLogFactory,
SchbrainMapPropertySource propertySource,
OrderedMapPropertySource propertySource,
ConfigurableProperties properties,
SpringApplication application) {
super(properties);
......
......@@ -2,7 +2,7 @@ package com.schbrain.framework.autoconfigure.apollo.util;
import com.ctrip.framework.apollo.Config;
import com.google.common.collect.Maps;
import com.schbrain.common.util.properties.SchbrainMapPropertySource;
import com.schbrain.common.util.properties.OrderedMapPropertySource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.ConfigurableEnvironment;
......@@ -19,7 +19,7 @@ import java.util.Set;
public class ConfigUtils {
@Nullable
public static SchbrainMapPropertySource toPropertySource(String name, Config config) {
public static OrderedMapPropertySource toPropertySource(String name, Config config) {
Set<String> propertyNames = config.getPropertyNames();
if (propertyNames.isEmpty()) {
return null;
......@@ -29,10 +29,10 @@ public class ConfigUtils {
String property = config.getProperty(propertyName, null);
configs.put(propertyName, property);
}
return new SchbrainMapPropertySource(name, configs);
return new OrderedMapPropertySource(name, configs);
}
public static void resolvePlaceHolders(ConfigurableEnvironment environment, SchbrainMapPropertySource propertySource) {
public static void resolvePlaceHolders(ConfigurableEnvironment environment, OrderedMapPropertySource propertySource) {
Map<String, Object> source = propertySource.getSource();
for (Entry<String, Object> entry : source.entrySet()) {
Object value = entry.getValue();
......
org.springframework.boot.env.EnvironmentPostProcessor=\
com.schbrain.framework.autoconfigure.apollo.ApolloConfigurationInitializer,\
com.schbrain.framework.autoconfigure.apollo.ApolloConfigurationInitializerEnvironmentPostProcessor,\
com.schbrain.framework.autoconfigure.apollo.ApolloPropertiesReorderEnvironmentPostProcessor
\ No newline at end of file
......@@ -129,6 +129,9 @@ public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> exte
if (this.bizIdColumnField != null) {
throw new BaseException(String.format("@BizId can't more than one in Class: \"%s\"", entityClass.getName()));
}
if (bizId.getType() != String.class) {
throw new BaseException("@BizId only support String field");
}
this.bizIdColumnField = new BizIdColumnField(entityClass, bizId);
BizIdHelper.putBizColumnField(entityClass, bizIdColumnField);
}, field -> field.isAnnotationPresent(BizId.class));
......
......@@ -7,8 +7,6 @@ import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import java.sql.SQLException;
/**
* @author liaozan
* @since 2023-04-17
......@@ -16,13 +14,12 @@ import java.sql.SQLException;
public class BizIdInjectInterceptor implements InnerInterceptor {
@Override
public void beforeUpdate(Executor executor, MappedStatement ms, Object entity) throws SQLException {
public void beforeUpdate(Executor executor, MappedStatement ms, Object entity) {
SqlCommandType sqlCommandType = ms.getSqlCommandType();
if (sqlCommandType != SqlCommandType.INSERT) {
return;
}
Class<?> entityClass = entity.getClass();
BizIdColumnField bizColumnField = BizIdHelper.getBizColumnField(entityClass);
BizIdColumnField bizColumnField = BizIdHelper.getBizColumnField(entity.getClass());
if (bizColumnField == null) {
return;
}
......
......@@ -4,8 +4,6 @@ import com.schbrain.framework.autoconfigure.oss.properties.OssProperties;
import com.schbrain.framework.autoconfigure.oss.util.OssUtils;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* @author liaozan
......@@ -15,9 +13,8 @@ import org.springframework.core.env.ConfigurableEnvironment;
@EnableConfigurationProperties(OssProperties.class)
public class OssAutoConfiguration {
public OssAutoConfiguration(ConfigurableApplicationContext applicationContext, OssProperties ossProperties) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
OssUtils.initialize(environment, ossProperties);
public OssAutoConfiguration(OssProperties ossProperties) {
OssUtils.initialize(ossProperties);
}
}
\ No newline at end of file
......@@ -22,7 +22,6 @@ import com.schbrain.framework.autoconfigure.oss.exception.OssException;
import com.schbrain.framework.autoconfigure.oss.properties.OssProperties;
import com.schbrain.framework.autoconfigure.oss.properties.OssProperties.StsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;
import java.io.File;
......@@ -48,7 +47,7 @@ public class OssUtils {
private static StsProperties stsProperties;
private static String directory;
public static void initialize(ConfigurableEnvironment environment, OssProperties properties) {
public static void initialize(OssProperties properties) {
if (properties == null || properties.isInValid()) {
log.warn("ossProperties is invalid, OssUtils will not available until reinitialize with the correct configuration");
return;
......@@ -60,7 +59,7 @@ public class OssUtils {
stsProperties = properties.getSts();
directory = properties.getDirectory();
if (directory == null) {
directory = ApplicationName.get(environment);
directory = ApplicationName.get();
}
} catch (Exception e) {
log.warn("oss initialize fail, OssUtils will not available until reinitialize with the correct configuration", e);
......
......@@ -9,7 +9,6 @@
<groupId>com.schbrain.framework</groupId>
<artifactId>schbrain-parent</artifactId>
<version>${revision}</version>
</parent>
<artifactId>starters</artifactId>
......
......@@ -10,7 +10,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.ConfigurableEnvironment;
import java.nio.file.Paths;
......@@ -25,15 +24,12 @@ public class XxlJobAutoConfiguration {
@Bean
@ConditionalOnMissingBean(XxlJobExecutor.class)
public SchbrainXxlJobExecutor schbrainXxlJobSpringExecutor(ConfigurableEnvironment environment,
XxlJobProperties xxlJobProperties,
LoggerProperties loggingProperties) {
String applicationName = ApplicationName.get(environment);
public SchbrainXxlJobExecutor schbrainXxlJobSpringExecutor(XxlJobProperties xxlJobProperties, LoggerProperties loggingProperties) {
SchbrainXxlJobExecutor executor = new SchbrainXxlJobExecutor();
executor.setAdminAddresses(xxlJobProperties.getAdminAddresses());
executor.setIp(xxlJobProperties.getIp());
executor.setPort(xxlJobProperties.getPort());
executor.setAppName(applicationName);
executor.setAppName(ApplicationName.get());
executor.setAccessToken(xxlJobProperties.getAccessToken());
executor.setLogPath(Paths.get(loggingProperties.getLogPath(), "xxl-job").toString());
executor.setLogRetentionDays(xxlJobProperties.getLogRetentionDays());
......
......@@ -2,25 +2,32 @@ package com.schbrain.framework.support.spring;
import lombok.Getter;
import org.apache.commons.logging.Log;
import org.springframework.boot.BootstrapContext;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.logging.DeferredLogFactory;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @author liaozan
* @since 2021/11/22
*/
@Getter
public abstract class EnvironmentPostProcessorLoggerAwareAdapter implements EnvironmentPostProcessor {
public abstract class LoggerAwareEnvironmentPostProcessor implements EnvironmentPostProcessor {
private final Log log;
private final DeferredLogFactory deferredLogFactory;
private final ConfigurableBootstrapContext bootstrapContext;
protected final Log log;
protected final DeferredLogFactory deferredLogFactory;
protected final ConfigurableBootstrapContext bootstrapContext;
public EnvironmentPostProcessorLoggerAwareAdapter(DeferredLogFactory logFactory, ConfigurableBootstrapContext bootstrapContext) {
public LoggerAwareEnvironmentPostProcessor(DeferredLogFactory logFactory, ConfigurableBootstrapContext bootstrapContext) {
this.log = logFactory.getLog(getClass());
this.bootstrapContext = bootstrapContext;
this.deferredLogFactory = logFactory;
this.bootstrapContext.addCloseListener(event -> onBootstrapContextClose(event.getBootstrapContext(), event.getApplicationContext()));
}
protected void onBootstrapContextClose(BootstrapContext bootstrapContext, ConfigurableApplicationContext applicationContext) {
}
}
\ No newline at end of file
......@@ -5,7 +5,7 @@ import cn.hutool.core.util.ArrayUtil;
import com.schbrain.common.constants.DateTimeFormatters;
import com.schbrain.common.util.EnvUtils;
import com.schbrain.common.util.PortUtils;
import com.schbrain.framework.support.spring.EnvironmentPostProcessorLoggerAwareAdapter;
import com.schbrain.framework.support.spring.LoggerAwareEnvironmentPostProcessor;
import org.springframework.boot.*;
import org.springframework.boot.actuate.autoconfigure.health.HealthProperties.Show;
import org.springframework.boot.actuate.info.InfoPropertiesInfoContributor.Mode;
......@@ -23,7 +23,7 @@ import java.util.*;
* @author liaozan
* @since 2021/12/18
*/
public class DefaultPropertiesEnvironmentPostProcessor extends EnvironmentPostProcessorLoggerAwareAdapter implements Ordered {
public class DefaultPropertiesEnvironmentPostProcessor extends LoggerAwareEnvironmentPostProcessor implements Ordered {
/**
* set default properties after configData loaded
......@@ -80,7 +80,7 @@ public class DefaultPropertiesEnvironmentPostProcessor extends EnvironmentPostPr
if (ArrayUtil.isEmpty(environment.getActiveProfiles())) {
environment.setActiveProfiles(EnvUtils.DEVELOPMENT);
defaultProperties.put(SPRING_PROFILE_ACTIVE, EnvUtils.DEVELOPMENT);
getLog().info(StrFormatter.format("{} is unset, set to {} by default", SPRING_PROFILE_ACTIVE, EnvUtils.DEVELOPMENT));
log.info(StrFormatter.format("{} is unset, set to {} by default", SPRING_PROFILE_ACTIVE, EnvUtils.DEVELOPMENT));
}
}
......@@ -92,8 +92,8 @@ public class DefaultPropertiesEnvironmentPostProcessor extends EnvironmentPostPr
return;
}
if (!environment.containsProperty(DUBBO_REGISTER_KEY)) {
getLog().info(StrFormatter.format("Not running on CloudPlatform, {} is set to false by default", DUBBO_REGISTER_KEY));
getLog().info(StrFormatter.format("If you want force to register with Dubbo Registry, set {} = true", DUBBO_REGISTER_KEY));
log.info(StrFormatter.format("Not running on CloudPlatform, {} is set to false by default", DUBBO_REGISTER_KEY));
log.info(StrFormatter.format("If you want force to register with Dubbo Registry, set {} = true", DUBBO_REGISTER_KEY));
defaultProperties.put(DUBBO_REGISTER_KEY, false);
}
}
......
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