Răsfoiți Sursa

系统优化

woody 1 an în urmă
părinte
comite
4d94fdb539

+ 1 - 3
framework-base/src/main/java/com/chelvc/framework/base/context/ApplicationContextHolder.java

@@ -104,9 +104,7 @@ public class ApplicationContextHolder implements ApplicationContextAware, Proper
 
     @Override
     public void refreshProperty(Set<String> properties) {
-        if (ObjectUtils.isEmpty(properties)) {
-            PROPERTY_OBJECT_MAPPING.clear();
-        } else {
+        if (ObjectUtils.notEmpty(properties)) {
             properties.forEach(PROPERTY_OBJECT_MAPPING::remove);
         }
     }

+ 5 - 0
framework-base/src/main/java/com/chelvc/framework/base/context/LoggingContextHolder.java

@@ -16,6 +16,11 @@ import org.slf4j.Logger;
  * @date 2024/1/30
  */
 public final class LoggingContextHolder {
+    /**
+     * 日志级别配置前缀
+     */
+    public static final String LOGGING_LEVEL_PREFIX = "logging.level.";
+
     private LoggingContextHolder() {
     }
 

+ 0 - 29
framework-base/src/main/java/com/chelvc/framework/base/interceptor/DynamicLoggingInterceptor.java

@@ -1,29 +0,0 @@
-package com.chelvc.framework.base.interceptor;
-
-import java.util.Objects;
-
-import ch.qos.logback.classic.Level;
-import ch.qos.logback.classic.Logger;
-import ch.qos.logback.classic.turbo.TurboFilter;
-import ch.qos.logback.core.spi.FilterReply;
-import com.chelvc.framework.base.context.ApplicationContextHolder;
-import org.slf4j.Marker;
-
-/**
- * 动态日志处理拦截器
- *
- * @author Woody
- * @date 2024/1/30
- */
-public class DynamicLoggingInterceptor extends TurboFilter {
-    @Override
-    public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
-        if (logger.getName().startsWith("ch.qos.logback.") || logger.getName().startsWith("org.springframework.")
-                || Objects.equals(logger.getName(), ApplicationContextHolder.class.getName())) {
-            return FilterReply.NEUTRAL;
-        } else if (ApplicationContextHolder.getProperty("logging.level." + logger.getName(), Level.class) == level) {
-            return FilterReply.ACCEPT;
-        }
-        return FilterReply.NEUTRAL;
-    }
-}

+ 77 - 5
framework-nacos/src/main/java/com/chelvc/framework/nacos/config/NacosConfigConfigurer.java

@@ -1,17 +1,28 @@
 package com.chelvc.framework.nacos.config;
 
-import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
 
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.LoggerContext;
 import com.alibaba.nacos.api.common.Constants;
 import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
 import com.alibaba.nacos.spring.context.event.config.NacosConfigReceivedEvent;
+import com.chelvc.framework.base.context.LoggingContextHolder;
+import com.chelvc.framework.common.util.ObjectUtils;
 import com.chelvc.framework.nacos.context.NacosContextHolder;
+import com.google.common.collect.Maps;
 import lombok.RequiredArgsConstructor;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.InitializingBean;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationListener;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.core.env.ConfigurableEnvironment;
+import org.springframework.core.env.PropertySource;
 
 /**
  * Nacos配置中心配置
@@ -25,12 +36,73 @@ import org.springframework.context.annotation.Configuration;
         groupId = "${nacos.config.group:" + Constants.DEFAULT_GROUP + "}", autoRefreshed = true)
 @NacosPropertySource(dataId = "${nacos.config.id:${spring.application.name}}",
         groupId = "${nacos.config.group:" + Constants.DEFAULT_GROUP + "}", autoRefreshed = true)
-public class NacosConfigConfigurer implements ApplicationListener<NacosConfigReceivedEvent> {
+public class NacosConfigConfigurer implements InitializingBean, ApplicationListener<NacosConfigReceivedEvent> {
     private final ApplicationContext applicationContext;
+    private final Map<String, Object> properties = Maps.newHashMap();
+
+    /**
+     * 重置Logger日志级别
+     *
+     * @param name  Logger名称
+     * @param level 日志级别
+     */
+    private void resetLoggerLevel(String name, String level) {
+        if (!name.startsWith(LoggingContextHolder.LOGGING_LEVEL_PREFIX)) {
+            return;
+        }
+        name = name.substring(LoggingContextHolder.LOGGING_LEVEL_PREFIX.length());
+        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
+        Logger logger = context.getLogger(name);
+        if (logger != null) {
+            logger.setLevel(ObjectUtils.ifNull(level, Level::toLevel));
+        }
+    }
+
+    @Override
+    public synchronized void afterPropertiesSet() throws Exception {
+        // 初始化Nacos当前配置,并根据配置重置日志级别
+        ConfigurableEnvironment environment = (ConfigurableEnvironment) this.applicationContext.getEnvironment();
+        for (PropertySource<?> source : environment.getPropertySources()) {
+            if (!(source instanceof com.alibaba.nacos.spring.core.env.NacosPropertySource)) {
+                continue;
+            }
+            Map<String, ?> properties = ((com.alibaba.nacos.spring.core.env.NacosPropertySource) source).getSource();
+            if (ObjectUtils.notEmpty(properties)) {
+                properties.forEach((key, value) -> {
+                    this.properties.put(key, value);
+                    this.resetLoggerLevel(key, ObjectUtils.ifNull(value, Object::toString));
+                });
+            }
+        }
+    }
 
     @Override
-    public void onApplicationEvent(NacosConfigReceivedEvent event) {
-        // 这里因Environment中的配置已被更新导致无法获取差异化配置项,故事件参数传空集合
-        this.applicationContext.publishEvent(new EnvironmentChangeEvent(Collections.emptySet()));
+    public synchronized void onApplicationEvent(NacosConfigReceivedEvent event) {
+        // 获取差异配置
+        Map<String, String> different = Maps.newHashMap();
+        Map<String, String> config = NacosContextHolder.analyseConfig(event.getContent());
+        config.forEach((key, value) -> {
+            if (!Objects.equals(value, this.properties.get(key))) {
+                different.put(key, value);
+            }
+        });
+        this.properties.forEach((key, value) -> {
+            String newest = config.get(key);
+            if (!Objects.equals(value, newest)) {
+                different.put(key, newest);
+            }
+        });
+
+        if (ObjectUtils.notEmpty(different)) {
+            // 重置当前配置
+            this.properties.clear();
+            this.properties.putAll(config);
+
+            // 重置日志级别
+            different.forEach(this::resetLoggerLevel);
+
+            // 发布环境配置变更事件
+            this.applicationContext.publishEvent(new EnvironmentChangeEvent(different.keySet()));
+        }
     }
 }

+ 6 - 5
framework-wechat/src/main/java/com/chelvc/framework/wechat/DefaultWechatPublicHandler.java

@@ -152,14 +152,15 @@ public class DefaultWechatPublicHandler implements WechatPublicHandler {
                      @NonNull Map<?, ?> parameters) {
         boolean debug = log.isDebugEnabled();
         if (debug) {
-            log.debug("Wechat public push request: {}, {}, {}", openid, template, parameters);
+            log.debug("Wechat public push request: {}, {}, {}, {}", openid, template, redirect, parameters);
         }
-        String appid = (redirect = redirect.trim()).isEmpty() ? StringUtils.EMPTY : this.properties.getAppid();
+        String applet = (redirect = redirect.trim()).isEmpty() ? StringUtils.EMPTY :
+                ObjectUtils.ifNull(this.properties.getPush().getApplet(), StringUtils.EMPTY);
         Map<String, Object> body = ImmutableMap.of(
                 "touser", openid,
                 "template_id", template,
                 "url", StringUtils.EMPTY,
-                "miniprogram", ImmutableMap.of("appid", appid, "pagepath", redirect),
+                "miniprogram", ImmutableMap.of("appid", applet, "pagepath", redirect),
                 "data", parameters
         );
         HttpHeaders headers = new HttpHeaders();
@@ -170,11 +171,11 @@ public class DefaultWechatPublicHandler implements WechatPublicHandler {
         try {
             response = WechatContextHolder.exchange(url, HttpMethod.POST, entity, WechatPublicMessage.class);
         } catch (Exception e) {
-            log.warn("Wechat public push failed: {}, {}, {}", openid, template, e.getMessage());
+            log.warn("Wechat public push failed: {}, {}, {}, {}", openid, template, redirect, e.getMessage());
             return 0;
         }
         if (debug) {
-            log.debug("Wechat public push response: {}, {}, {}", openid, template, response);
+            log.debug("Wechat public push response: {}", response);
         }
         return response.getId();
     }

+ 17 - 1
framework-wechat/src/main/java/com/chelvc/framework/wechat/config/WechatProperties.java

@@ -46,7 +46,7 @@ public class WechatProperties {
         /**
          * 是否可刷新
          */
-        private boolean refreshable = true;
+        private boolean refreshable;
     }
 
     /**
@@ -99,6 +99,11 @@ public class WechatProperties {
          * AppSecret
          */
         private String secret;
+
+        /**
+         * 消息推送配置
+         */
+        private final Push push = new Push();
     }
 
     /**
@@ -136,4 +141,15 @@ public class WechatProperties {
          */
         private String callback;
     }
+
+    /**
+     * 公众号消息推送配置
+     */
+    @Data
+    public static class Push {
+        /**
+         * 小程序标识
+         */
+        private String applet;
+    }
 }

+ 3 - 1
framework-wechat/src/main/java/com/chelvc/framework/wechat/context/WechatContextHolder.java

@@ -137,7 +137,9 @@ public final class WechatContextHolder implements ApplicationRunner {
                     long duration = accessToken.getDuration();
                     RedisContextHolder.getDefaultTemplate().opsForValue().set(key, token, duration, TimeUnit.SECONDS);
                     APP_TOKEN_MAPPING.put(appid, token);
-                    log.info("Wechat access token refreshed: {}", appid);
+                    if (log.isDebugEnabled()) {
+                        log.debug("Wechat access token refreshed: {}, {}", appid, token);
+                    }
                 }
             });
         } catch (Exception e) {