Quellcode durchsuchen

version 2.0.0 publish

张泳健 vor 5 Jahren
Ursprung
Commit
6539a27979

+ 8 - 1
README.md Datei anzeigen

@@ -5,4 +5,11 @@
5 5
 mvn clean compile package install 
6 6
 ```
7 7
 
8
-## [仿SpringBoot属性文件加载](./configuration-loader/README.md)
8
+## [仿SpringBoot属性文件加载](./configuration-loader/README.md)
9
+
10
+---
11
+
12
+## [日志重写](./log-setter/README.md)
13
+
14
+---
15
+

+ 46 - 0
configuration-loader-test/README.md Datei anzeigen

@@ -0,0 +1,46 @@
1
+# configuration-loader 使用
2
+
3
+## 使用lombok简单化set/get方法
4
+pom.xml 添加
5
+```xml
6
+<dependency>
7
+    <groupId>org.projectlombok</groupId>
8
+    <artifactId>lombok</artifactId>
9
+    <version>1.18.10</version>
10
+    <scope>provided</scope>
11
+</dependency>
12
+```
13
+
14
+- [最新版本见: https://mvnrepository.com/artifact/org.projectlombok/lombok/1.18.10](https://mvnrepository.com/artifact/org.projectlombok/lombok/1.18.10)
15
+
16
+## 属性文件的定义
17
+### yml/yaml 文件的定义
18
+- [**application.yml**](./config/application.yml)
19
+- [**application-dev.yml**](./config/application-dev.yml)
20
+
21
+### properties
22
+- [application.properties](./config/application.properties)
23
+- [application-dev.properties](./config/application-dev.properties)
24
+
25
+### json
26
+- [application.json](./config/application.json)
27
+- [application-dev.json](./config/application-dev.json)
28
+
29
+
30
+## 类的定义
31
+>这里使用`lombok`插件生成`set`和`get`方法,使用注解`@lombok.Data`,如果不使用`lombok`,就手动生成set和get方法就可以了.
32
+
33
+
34
+[**me.yuxiaoyao.loader.test.PropertiesConfig.java**](./src/main/java/me/yuxiaoyao/loader/test/PropertiesConfig.java)
35
+
36
+
37
+
38
+>当属性名和JAVA字段名不一致时,可以使用 注解 `@JsonProperty("gw-config")` 修饰字段.
39
+
40
+
41
+## [运行DEMO](./src/main/java/me/yuxiaoyao/loader/test/ConfigurationLoaderTest.java)
42
+[me.yuxiaoyao.loader.test.ConfigurationLoaderTest](./src/main/java/me/yuxiaoyao/loader/test/ConfigurationLoaderTest.java)
43
+
44
+运行有问题请看:
45
+![1](./art/1.png)
46
+![2](./art/2.png)

BIN
configuration-loader-test/art/1.png Datei anzeigen


BIN
configuration-loader-test/art/2.png Datei anzeigen


+ 64 - 0
configuration-loader-test/config/application-dev.json Datei anzeigen

@@ -0,0 +1,64 @@
1
+{
2
+  "type": "json",
3
+  "server": {
4
+    "port": 8083,
5
+    "mysql": {
6
+      "url": "jdbc:mysql://127.0.0.1:3306/test",
7
+      "class-name": "com.myqsl",
8
+      "password": "password",
9
+      "username": "root"
10
+    },
11
+    "redis": {
12
+      "enable": true,
13
+      "host": "127.0.0.1",
14
+      "port": 6379,
15
+      "password": null,
16
+      "database": 1,
17
+      "thread-pool": {
18
+        "max": 10,
19
+        "min-idle-timeout": 100
20
+      }
21
+    }
22
+  },
23
+  "gw-config": {
24
+    "gateway-no": 11,
25
+    "simple-list": [
26
+      "list1",
27
+      "list2",
28
+      "list3"
29
+    ],
30
+    "cmd-list": [
31
+      {
32
+        "name": "msg",
33
+        "type": 1
34
+      },
35
+      {
36
+        "name": "cmdResponse",
37
+        "type": 2
38
+      },
39
+      {
40
+        "name": "test",
41
+        "type": 3
42
+      }
43
+    ],
44
+    "simple-map": {
45
+      "skey1": "value1",
46
+      "skey2": "value2",
47
+      "skey3": "value3"
48
+    },
49
+    "cmd-map": {
50
+      "key1": {
51
+        "name": "value-name1",
52
+        "type": "value-type1"
53
+      },
54
+      "key2": {
55
+        "name": "value-name2",
56
+        "type": "value-type2"
57
+      },
58
+      "key3": {
59
+        "name": "value-name3",
60
+        "type": "value-type3"
61
+      }
62
+    }
63
+  }
64
+}

+ 32 - 0
configuration-loader-test/config/application-dev.properties Datei anzeigen

@@ -0,0 +1,32 @@
1
+type=properties
2
+server.port=8083
3
+server.mysql.url=jdbc:mysql://127.0.0.1:3306/test
4
+server.mysql.class-name=com.myqsl
5
+server.mysql.password=password
6
+server.mysql.username=root
7
+server.redis.enable=true
8
+server.redis.host=127.0.0.1
9
+server.redis.port=6379
10
+server.redis.password=
11
+server.redis.database=1
12
+server.redis.thread-pool.max=10
13
+server.redis.thread-pool.min-idle-timeout=100
14
+gw-config.gateway-no=11
15
+gw-config.simple-list[0]=list1
16
+gw-config.simple-list[1]=list2
17
+gw-config.simple-list[2]=list3
18
+gw-config.cmd-list[0].name=msg
19
+gw-config.cmd-list[0].type=1
20
+gw-config.cmd-list[1].name=cmdResponse
21
+gw-config.cmd-list[1].type=2
22
+gw-config.cmd-list[2].name=test
23
+gw-config.cmd-list[2].type=3
24
+gw-config.simple-map.skey1=value1
25
+gw-config.simple-map.skey2=value2
26
+gw-config.simple-map.skey3=value3
27
+gw-config.cmd-map.key1.name=value-name1
28
+gw-config.cmd-map.key1.type=value-type1
29
+gw-config.cmd-map.key2.name=value-name2
30
+gw-config.cmd-map.key2.type=value-type2
31
+gw-config.cmd-map.key3.name=value-name3
32
+gw-config.cmd-map.key3.type=value-type3

+ 40 - 2
configuration-loader-test/config/application-dev.yml Datei anzeigen

@@ -1,5 +1,15 @@
1
-web:
1
+# string
2
+type: yml
3
+server:
4
+  # integer
5
+  port: 8083
6
+  mysql:
7
+    url: jdbc:mysql://127.0.0.1:3306/test
8
+    class-name: com.myqsl
9
+    password: password
10
+    username: root
2 11
   redis:
12
+    # boolean
3 13
     enable: true
4 14
     host: 127.0.0.1
5 15
     port: 6379
@@ -8,7 +18,35 @@ web:
8 18
     thread-pool:
9 19
       max: 10
10 20
       min-idle-timeout: 100
11
-
12 21
 gw-config:
13 22
   gateway-no: 11
23
+  # simple list
24
+  simple-list:
25
+    - list1
26
+    - list2
27
+    - list3
28
+  # list
29
+  cmd-list:
30
+    - name: msg
31
+      type: 1
32
+    - name: cmdResponse
33
+      type: 2
34
+    - name: test
35
+      type: 3
36
+  # simple map
37
+  simple-map:
38
+    skey1: value1
39
+    skey2: value2
40
+    skey3: value3
41
+  # map
42
+  cmd-map:
43
+    key1:
44
+      name: value-name1
45
+      type: value-type1
46
+    key2:
47
+      name: value-name2
48
+      type: value-type2
49
+    key3:
50
+      name: value-name3
51
+      type: value-type3
14 52
 

+ 5 - 0
configuration-loader-test/config/application.json Datei anzeigen

@@ -0,0 +1,5 @@
1
+{
2
+  "profile": {
3
+    "active": "dev"
4
+  }
5
+}

+ 1 - 0
configuration-loader-test/config/application.properties Datei anzeigen

@@ -0,0 +1 @@
1
+profile.active=dev

+ 6 - 1
configuration-loader-test/pom.xml Datei anzeigen

@@ -5,7 +5,7 @@
5 5
     <parent>
6 6
         <artifactId>lang-utils</artifactId>
7 7
         <groupId>me.yuxiaoyao.lang</groupId>
8
-        <version>1.0.0</version>
8
+        <version>2.0.0</version>
9 9
     </parent>
10 10
     <modelVersion>4.0.0</modelVersion>
11 11
 
@@ -29,6 +29,11 @@
29 29
             <version>${jackson.version}</version>
30 30
         </dependency>
31 31
 
32
+        <dependency>
33
+            <groupId>org.projectlombok</groupId>
34
+            <artifactId>lombok</artifactId>
35
+            <scope>provided</scope>
36
+        </dependency>
32 37
 
33 38
         <dependency>
34 39
             <groupId>org.junit.jupiter</groupId>

+ 32 - 0
configuration-loader-test/src/main/java/me/yuxiaoyao/loader/test/ConfigurationLoaderTest.java Datei anzeigen

@@ -0,0 +1,32 @@
1
+package me.yuxiaoyao.loader.test;
2
+
3
+
4
+import me.yuxiaoyao.config.loader.ConfigLoader;
5
+
6
+import java.util.Map;
7
+
8
+/**
9
+ * @author Kerry on 19/10/28
10
+ */
11
+
12
+public class ConfigurationLoaderTest {
13
+    public static void main(String[] args) {
14
+
15
+        // 回调告诉最终启用了哪个 profile
16
+        ConfigLoader.parseConfig(args, PropertiesConfig.class, new ConfigLoader.ConfigListener() {
17
+            @Override
18
+            public void activeProfile(String profile) {
19
+                System.out.println("当前active profile = " + profile);
20
+            }
21
+        });
22
+
23
+        // 不回调
24
+        final PropertiesConfig propertiesConfig = ConfigLoader.parseConfig(PropertiesConfig.class);
25
+
26
+        final Map<String, PropertiesConfig.GwConfigBean.MapKeyBean> cmdMap = propertiesConfig.getGwConfig().getCmdMap();
27
+        cmdMap.forEach((k, v) -> System.out.println("key = [" + k + "]. values = [" + v + "]."));
28
+
29
+        System.out.println(propertiesConfig);
30
+
31
+    }
32
+}

+ 86 - 0
configuration-loader-test/src/main/java/me/yuxiaoyao/loader/test/PropertiesConfig.java Datei anzeigen

@@ -0,0 +1,86 @@
1
+package me.yuxiaoyao.loader.test;
2
+
3
+
4
+import com.fasterxml.jackson.annotation.JsonProperty;
5
+
6
+import java.util.List;
7
+import java.util.Map;
8
+
9
+/**
10
+ * @author Kerry on 19/10/28
11
+ */
12
+
13
+@lombok.Data
14
+public class PropertiesConfig {
15
+
16
+
17
+    private String type;
18
+    private ServerBean server;
19
+
20
+    @JsonProperty("gw-config")
21
+    private GwConfigBean gwConfig;
22
+
23
+    @lombok.Data
24
+    public static class ServerBean {
25
+        private Integer port;
26
+        private MysqlBean mysql;
27
+        private RedisBean redis;
28
+
29
+        @lombok.Data
30
+        public static class MysqlBean {
31
+            private String url;
32
+            private String classname;
33
+            private String password;
34
+            private String username;
35
+        }
36
+
37
+        @lombok.Data
38
+        public static class RedisBean {
39
+            private Boolean enable;
40
+            private String host;
41
+            private Integer port;
42
+            private String password;
43
+            private Integer database;
44
+            @JsonProperty("thread-pool")
45
+            private ThreadPoolBean threadPool;
46
+
47
+            @lombok.Data
48
+            public static class ThreadPoolBean {
49
+                private int max;
50
+                @JsonProperty("min-idle-timeout")
51
+                private int minIdleTimeout;
52
+            }
53
+        }
54
+    }
55
+
56
+    @lombok.Data
57
+    public static class GwConfigBean {
58
+
59
+        @JsonProperty("gateway-no")
60
+        private Integer gatewayNo;
61
+
62
+        @JsonProperty("simple-list")
63
+        private List<String> simpleList;
64
+
65
+        @JsonProperty("cmd-list")
66
+        private List<CmdListBean> cmdList;
67
+
68
+        @JsonProperty("simple-map")
69
+        private Map<String, String> simpleMap;
70
+
71
+        @JsonProperty("cmd-map")
72
+        private Map<String, MapKeyBean> cmdMap;
73
+
74
+        @lombok.Data
75
+        public static class CmdListBean {
76
+            private String name;
77
+            private int type;
78
+        }
79
+
80
+        @lombok.Data
81
+        public static class MapKeyBean {
82
+            private String name;
83
+            private String type;
84
+        }
85
+    }
86
+}

+ 7 - 0
configuration-loader-test/src/test/java/me/yuxiaoyao/loader/test/ConfigurationLoaderTestTest.java Datei anzeigen

@@ -0,0 +1,7 @@
1
+package me.yuxiaoyao.loader.test;
2
+
3
+import static org.junit.jupiter.api.Assertions.*;
4
+
5
+class ConfigurationLoaderTestTest {
6
+
7
+}

+ 34 - 82
configuration-loader/README.md Datei anzeigen

@@ -2,29 +2,28 @@
2 2
 
3 3
 > 一般Java应用程序中,用于加载属性文件
4 4
 
5
-
6
-maven
5
+### maven 必须
7 6
 ```
8 7
 <dependency>
9 8
     <groupId>me.yuxiaoyao.lang</groupId>
10 9
     <artifactId>configuration-loader</artifactId>
11
-    <version>1.0.0</version>
10
+    <version>2.0.0</version>
12 11
 </dependency>
13
-```
14
-
15
-[最新版本见:pom.xml](./pom.xml)
16
-
17
-## 依赖
18
-
19
-### 1.必须的依赖
20
-```xml
21 12
 <dependency>
22 13
     <groupId>com.fasterxml.jackson.core</groupId>
23 14
     <artifactId>jackson-databind</artifactId>
24
-    <version>${jackson.version}</version>
15
+    <version>2.10.0</version>
25 16
 </dependency>
26 17
 ```
27
-### 2. 可先依赖(至少有一个,或者两个都加)
18
+
19
+- [`configuration-loader`最新版本见:pom.xml](./pom.xml)
20
+- [`jackson-databind`最新版见:](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind)
21
+
22
+
23
+
24
+### 可选依赖(可以不加,也可以选一个加,或者都加)
25
+
26
+#### 加载yml/yaml 文件时必须加
28 27
 ```xml
29 28
 <!-- yml/yaml -->
30 29
 <dependency>
@@ -32,7 +31,10 @@ maven
32 31
     <artifactId>jackson-dataformat-yaml</artifactId>
33 32
     <version>${jackson.version}</version>
34 33
 </dependency>
34
+```
35 35
 
36
+#### 加载 properties 文件时必须加
37
+```
36 38
 <!-- properties -->
37 39
 <dependency>
38 40
     <groupId>com.fasterxml.jackson.dataformat</groupId>
@@ -40,79 +42,29 @@ maven
40 42
     <version>${jackson.version}</version>
41 43
 </dependency>
42 44
 ```
43
-如果两个依赖都加的话,文件后缀顺序为:
44
-
45
-1. yml - jackson-dataformat-yaml
46
-2. yaml - jackson-dataformat-yaml
47
-3. properties - jackson-dataformat-properties
48
-
49
-## 用法
50
-ConnectorProperties.java
51
-```java
52
-@Data
53
-public class ConnectorProperties {
54
-
55
-    private Connector connector;
56
-    private Transfer transfer;
57
-    private Redis redis;
58
-
59
-    @Data
60
-    public static class Connector {
61
-        private Integer port;
62
-    }
63
-
64
-    @Data
65
-    public static class Transfer {
66
-        private List<String> urls;
67
-        @JsonProperty("test-info")
68
-        private String testInfo;
69
-    }
70
-
71
-    @Data
72
-    public static class Redis {
73
-        private String host;
74
-        private Integer port;
75
-        private String password;
76
-        private int database;
77
-    }
78
-
79
-}
80
-```
81
-application.yml
82
-```yaml
83
-profile:
84
-  active: dev
85
-```
86 45
 
87
-application-dev.yml
88
-```yaml
89
-connector:
90
-  port: 9081
91
-transfer:
92
-  # all transfer services url
93
-  urls: [127.0.0.1:9082]
94
-  test-info: test-info-content
95
-redis:
96
-  host: ${connector.port}
97
-  port: 6379
98
-  password:
99
-  dababase: 0
100
-```
46
+#### 以上两个都不加时,默认使用`json`
101 47
 
102
-默认的配置文件为`application.yml/application.yaml/application.properties`
48
+#### 说明
49
+配置文件放在`config`目录下. 
103 50
 
104
-基本用法
105
-```java
106
-ConnectorProperties connectorProperties = ConfigLoader.parseConfig(ConnectorProperties.class);
107 51
 ```
52
+maven 项目
53
+    | - config
54
+        | - application.yml
55
+        | - application-dev.yml
56
+    | - src
57
+        | - main
108 58
 
109
-用法:
110
-```
111
-LogSetter.resetLogger();
112
-ConnectorProperties connectorProperties = ConfigLoader.parseConfig(args, ConnectorProperties.class, profile -> {
113
-    LogSetter.setLogback("logback", profile);
114
-});
115 59
 ```
116 60
 
117
-**字段和属性名不一致时:**
118
-使用`@JsonProperty("原属性名")` 修饰字段
61
+
62
+>如果两个依赖都加的话,文件后缀顺序为:
63
+
64
+1. `yml` - jackson-dataformat-yaml
65
+2. `yaml` - jackson-dataformat-yaml
66
+3. `properties` - jackson-dataformat-properties
67
+4. `json` - default
68
+
69
+
70
+## [使用方法和DEMO](../configuration-loader-test/README.md)

+ 1 - 13
configuration-loader/pom.xml Datei anzeigen

@@ -5,7 +5,7 @@
5 5
     <parent>
6 6
         <artifactId>lang-utils</artifactId>
7 7
         <groupId>me.yuxiaoyao.lang</groupId>
8
-        <version>1.0.0</version>
8
+        <version>2.0.0</version>
9 9
     </parent>
10 10
     <modelVersion>4.0.0</modelVersion>
11 11
 
@@ -13,18 +13,6 @@
13 13
 
14 14
 
15 15
     <dependencies>
16
-        <dependency>
17
-            <groupId>org.slf4j</groupId>
18
-            <artifactId>slf4j-api</artifactId>
19
-        </dependency>
20
-        <dependency>
21
-            <groupId>org.slf4j</groupId>
22
-            <artifactId>jul-to-slf4j</artifactId>
23
-        </dependency>
24
-        <dependency>
25
-            <groupId>org.slf4j</groupId>
26
-            <artifactId>log4j-over-slf4j</artifactId>
27
-        </dependency>
28 16
 
29 17
         <!-- json -->
30 18
         <dependency>

+ 99 - 81
configuration-loader/src/main/java/me/yuxiaoyao/config/loader/ConfigLoader.java Datei anzeigen

@@ -29,30 +29,66 @@ public class ConfigLoader {
29 29
     private static String START_PLACEHOLDER = "${";
30 30
     private static String END_PLACEHOLDER = "}";
31 31
 
32
-
33
-    private enum ConfigProtocol {
32
+    private enum MapperFactoryEnum {
34 33
         /**
35
-         * 文件
34
+         * yml
36 35
          */
37
-        FILE(1),
36
+        YML("yml", "com.fasterxml.jackson.dataformat.yaml.YAMLFactory"),
38 37
         /**
39
-         * 类路径
38
+         * yaml
40 39
          */
41
-        CLASSPATH(0);
42
-
40
+        YAML("yaml", "com.fasterxml.jackson.dataformat.yaml.YAMLFactory"),
41
+        /**
42
+         * properties
43
+         */
44
+        PROPERTIES("properties", "com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper"),
43 45
         /**
44
-         * 配置文件优先级
46
+         * default json
45 47
          */
46
-        private int order;
48
+        JSON("json", ObjectMapper.class.getCanonicalName());
49
+        private String name;
50
+        private Class<?> factory;
51
+
52
+        MapperFactoryEnum(String name, String className) {
53
+            this.name = name;
54
+            this.factory = findClass(className);
55
+        }
56
+
57
+        private static Class<?> findClass(String classname) {
58
+            try {
59
+                return Class.forName(classname);
60
+            } catch (ClassNotFoundException ignored) {
61
+            }
62
+            return null;
63
+        }
64
+
65
+        public String getName() {
66
+            return name;
67
+        }
47 68
 
48
-        ConfigProtocol(int order) {
49
-            this.order = order;
69
+        public Class<?> getFactory() {
70
+            return factory;
50 71
         }
51 72
 
52
-        public static List<ConfigProtocol> sortList() {
53
-            List<ConfigProtocol> configProtocols = new ArrayList<>(Arrays.asList(values()));
54
-            configProtocols.sort((o1, o2) -> o2.order - o1.order);
55
-            return configProtocols;
73
+        public ObjectMapper getObjectMapper() {
74
+            if (factory == null) {
75
+                return null;
76
+            }
77
+            try {
78
+                final Object o = factory.newInstance();
79
+                ObjectMapper objectMapper;
80
+                if (this == MapperFactoryEnum.YML || this == MapperFactoryEnum.YAML) {
81
+                    objectMapper = new ObjectMapper((JsonFactory) o);
82
+                } else {
83
+                    objectMapper = (ObjectMapper) o;
84
+                }
85
+                objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
86
+                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
87
+                return objectMapper;
88
+            } catch (InstantiationException | IllegalAccessException e) {
89
+                e.printStackTrace();
90
+            }
91
+            return null;
56 92
         }
57 93
     }
58 94
 
@@ -63,38 +99,35 @@ public class ConfigLoader {
63 99
          * @param profile
64 100
          */
65 101
         void activeProfile(String profile);
102
+
66 103
     }
67 104
 
105
+
68 106
     /**
69 107
      * 返回数据流
70 108
      *
71
-     * @param configProtocol
72 109
      * @param path
73 110
      * @return 结果可能为 null
74 111
      */
75
-    private static InputStream getConfigFileAsStream(ConfigProtocol configProtocol, String path) {
76
-
77
-        switch (configProtocol) {
78
-            case FILE:
79
-                try {
80
-                    return new FileInputStream(new File(DEFAULT_FILE_CONFIG_FOLDER + File.separator + path));
81
-                } catch (FileNotFoundException ignored) {
82
-                }
83
-                return null;
84
-            case CLASSPATH:
85
-                return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
86
-            default:
87
-                throw new Error("not support this path = " + path);
112
+    private static InputStream getConfigFileAsStream(String path) {
113
+        try {
114
+            // from config path
115
+            final File file = new File(DEFAULT_FILE_CONFIG_FOLDER + File.separator + path);
116
+            if (file.exists()) {
117
+                return new FileInputStream(file);
118
+            }
119
+        } catch (FileNotFoundException ignored) {
88 120
         }
121
+        // from class path
122
+        return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
89 123
     }
90 124
 
91
-
92 125
     public static <T> T parseConfig(Class<T> clazz) {
93 126
         return parseConfig(null, clazz, null);
94 127
     }
95 128
 
96 129
     public static <T> T parseConfig(String[] args, Class<T> clazz, ConfigListener configListener) {
97
-        LinkedHashMap map = loaderConfig(args, configListener);
130
+        Map map = loaderConfig(args, configListener);
98 131
         return getObjectMapper().convertValue(map, clazz);
99 132
     }
100 133
 
@@ -104,7 +137,7 @@ public class ConfigLoader {
104 137
     }
105 138
 
106 139
     public static <T> T parseConfig(String[] args, TypeReference<T> toValueTypeRef, ConfigListener configListener) {
107
-        LinkedHashMap map = loaderConfig(args, configListener);
140
+        Map map = loaderConfig(args, configListener);
108 141
         return getObjectMapper().convertValue(map, toValueTypeRef);
109 142
     }
110 143
 
@@ -120,90 +153,75 @@ public class ConfigLoader {
120 153
      *
121 154
      * @return
122 155
      */
123
-    public static LinkedHashMap loaderConfig() {
156
+    public static Map loaderConfig() {
124 157
         return loaderConfig(null, null);
125 158
     }
126 159
 
160
+
127 161
     /**
128 162
      * 加载指定 profile 的配置文件
129 163
      *
130 164
      * @param args
131 165
      * @return
132 166
      */
133
-    public static LinkedHashMap loaderConfig(String[] args, ConfigListener configListener) {
134
-
135
-        List<ConfigProtocol> configProtocols = ConfigProtocol.sortList();
136
-        LinkedHashMap defaultProperties = null;
137
-        ConfigProtocol matchProtocol = null;
138
-        for (ConfigProtocol protocol : configProtocols) {
139
-            LinkedHashMap temp = selectConfig(protocol, DEFAULT_APPLICATION);
140
-            if (temp != null) {
141
-                defaultProperties = temp;
142
-                matchProtocol = protocol;
143
-                break;
144
-            }
145
-        }
167
+    public static Map loaderConfig(String[] args, ConfigListener configListener) {
168
+
169
+        Map defaultProperties = selectConfigPosition(DEFAULT_APPLICATION);
146 170
         if (defaultProperties == null) {
147 171
             return null;
148 172
         }
149
-
150 173
         String profile = getProfileByArgs(args);
151
-
152 174
         if (profile == null || profile.length() == 0) {
153 175
             profile = getActiveProfile(defaultProperties);
154 176
         }
155 177
         if (configListener != null) {
178
+            // callback
156 179
             configListener.activeProfile(profile);
157 180
         }
158
-        LinkedHashMap map = selectConfig(matchProtocol, DEFAULT_APPLICATION + "-" + profile);
159
-        if (map != null) {
160
-            removeActiveProfile(map);
181
+        Map profileMap = selectConfigPosition(DEFAULT_APPLICATION + "-" + profile);
182
+        if (profileMap != null) {
183
+            removeActiveProfile(profileMap);
161 184
             //noinspection unchecked
162
-            defaultProperties.putAll(map);
185
+            defaultProperties.putAll(profileMap);
163 186
         }
164 187
         return propertiesHandler(defaultProperties);
165 188
     }
166 189
 
167 190
 
168
-    private static LinkedHashMap selectConfig(ConfigProtocol configProtocol, String filePrefix) {
169
-        InputStream configFileAsStream = getConfigFileAsStream(configProtocol, filePrefix + ".yml");
170
-        if (configFileAsStream == null) {
171
-            configFileAsStream = getConfigFileAsStream(configProtocol, filePrefix + ".yaml");
172
-        }
173
-        Object yamlFactory = null;
174
-        try {
175
-            Class<?> factory = Class.forName("com.fasterxml.jackson.dataformat.yaml.YAMLFactory");
176
-            yamlFactory = factory.newInstance();
177
-        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
178
-            // e.printStackTrace();
179
-        }
180
-        ObjectMapper objectMapper = null;
181
-        if (configFileAsStream != null && yamlFactory != null) {
182
-            objectMapper = new ObjectMapper((JsonFactory) yamlFactory);
183
-        } else {
184
-            configFileAsStream = getConfigFileAsStream(configProtocol, filePrefix + ".properties");
185
-            try {
186
-                Class<?> javaProps = Class.forName("com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper");
187
-                objectMapper = (ObjectMapper) javaProps.newInstance();
188
-            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
189
-                // e.printStackTrace();
191
+    private static Map selectConfigPosition(String baseFilename) {
192
+        InputStream configFileAsStream = null;
193
+        MapperFactoryEnum parseType = null;
194
+        for (MapperFactoryEnum value : MapperFactoryEnum.values()) {
195
+            if (value.getFactory() == null) {
196
+                continue;
197
+            }
198
+            configFileAsStream = getConfigFileAsStream(baseFilename + "." + value.getName());
199
+            if (configFileAsStream != null) {
200
+                parseType = value;
201
+                break;
190 202
             }
191 203
         }
192
-        if (objectMapper == null) {
193
-            throw new Error("jackson dependencies at least container [jackson-dataformat-yaml] or [jackson-dataformat-properties].");
204
+        if (parseType == null) {
205
+            return null;
194 206
         }
195
-        if (configFileAsStream == null) {
207
+        ObjectMapper objectMapper = parseType.getObjectMapper();
208
+        if (objectMapper == null) {
196 209
             return null;
197 210
         }
198 211
         try {
199 212
             return objectMapper.readValue(configFileAsStream, LinkedHashMap.class);
200 213
         } catch (IOException e) {
201 214
             e.printStackTrace();
215
+        } finally {
216
+            try {
217
+                configFileAsStream.close();
218
+            } catch (IOException e) {
219
+                e.printStackTrace();
220
+            }
202 221
         }
203 222
         return null;
204 223
     }
205 224
 
206
-
207 225
     private static String getActiveProfile(Map fileMap) {
208 226
         Object profile = fileMap.get(PROFILE);
209 227
         if (profile instanceof Map) {
@@ -228,7 +246,7 @@ public class ConfigLoader {
228 246
      * @param map
229 247
      * @return
230 248
      */
231
-    private static LinkedHashMap propertiesHandler(LinkedHashMap map) {
249
+    private static Map propertiesHandler(Map map) {
232 250
         Map<Object, String> preHandler = new LinkedHashMap<>();
233 251
         // find placeholder value
234 252
         findPreResolveProperties(map, preHandler, null);
@@ -358,8 +376,8 @@ public class ConfigLoader {
358 376
         if (args != null && args.length > 0) {
359 377
             for (String arg : args) {
360 378
                 arg = arg.trim();
361
-                if (arg.startsWith("--profile=")) {
362
-                    return arg.substring("--profile=".length());
379
+                if (arg.startsWith("--profile.active=")) {
380
+                    return arg.substring("--profile.active=".length());
363 381
                 }
364 382
             }
365 383
         }

+ 39 - 0
log-setter/README.md Datei anzeigen

@@ -0,0 +1,39 @@
1
+
2
+# 日志重定向
3
+
4
+## Maven
5
+```xml
6
+<dependencies>
7
+        
8
+    <dependency>
9
+        <groupId>me.yuxiaoyao.lang</groupId>
10
+        <artifactId>log-setter</artifactId>
11
+        <version>2.0.0</version>
12
+    </dependency>
13
+
14
+    <dependency>
15
+        <groupId>org.slf4j</groupId>
16
+        <artifactId>slf4j-api</artifactId>
17
+    </dependency>
18
+    <dependency>
19
+        <groupId>org.slf4j</groupId>
20
+        <artifactId>jul-to-slf4j</artifactId>
21
+    </dependency>
22
+    <dependency>
23
+        <groupId>org.slf4j</groupId>
24
+        <artifactId>log4j-over-slf4j</artifactId>
25
+    </dependency>
26
+    <dependency>
27
+        <groupId>ch.qos.logback</groupId>
28
+        <artifactId>logback-classic</artifactId>
29
+    </dependency>
30
+
31
+</dependencies>
32
+
33
+```
34
+
35
+## 用法
36
+```
37
+LogSetter.resetLogger();
38
+LogSetter.setLogback("logback","profile");
39
+```

+ 1 - 1
log-setter/pom.xml Datei anzeigen

@@ -5,7 +5,7 @@
5 5
     <parent>
6 6
         <artifactId>lang-utils</artifactId>
7 7
         <groupId>me.yuxiaoyao.lang</groupId>
8
-        <version>1.0.0</version>
8
+        <version>2.0.0</version>
9 9
     </parent>
10 10
     <modelVersion>4.0.0</modelVersion>
11 11
 

configuration-loader/src/main/java/me/yuxiaoyao/config/log/LogSetter.java → log-setter/src/main/java/me/yuxiaoyao/config/log/LogSetter.java Datei anzeigen

@@ -1,6 +1,5 @@
1 1
 package me.yuxiaoyao.config.log;
2 2
 
3
-import me.yuxiaoyao.config.loader.ConfigLoader;
4 3
 import org.slf4j.bridge.SLF4JBridgeHandler;
5 4
 
6 5
 import java.io.File;
@@ -10,6 +9,7 @@ import java.io.File;
10 9
  */
11 10
 
12 11
 public class LogSetter {
12
+    public static String DEFAULT_FILE_CONFIG_FOLDER = "config";
13 13
 
14 14
     public static void resetLogger() {
15 15
         // 第三方JAR包引用了 其他日志LIB,这里统一用 slf4j 统一接管
@@ -22,12 +22,12 @@ public class LogSetter {
22 22
         if (profile == null) {
23 23
             return;
24 24
         }
25
-        File file = new File(ConfigLoader.DEFAULT_FILE_CONFIG_FOLDER + File.separator + basename + "-" + profile + ".xml");
25
+        File file = new File(DEFAULT_FILE_CONFIG_FOLDER + File.separator + basename + "-" + profile + ".xml");
26 26
         if (file.exists()) {
27 27
             System.setProperty("logback.configurationFile", file.getAbsolutePath());
28 28
             return;
29 29
         }
30
-        file = new File(ConfigLoader.DEFAULT_FILE_CONFIG_FOLDER + File.separator + basename + ".xml");
30
+        file = new File(DEFAULT_FILE_CONFIG_FOLDER + File.separator + basename + ".xml");
31 31
         if (file.exists()) {
32 32
             System.setProperty("logback.configurationFile", file.getAbsolutePath());
33 33
         }

+ 2 - 1
pom.xml Datei anzeigen

@@ -7,7 +7,8 @@
7 7
     <groupId>me.yuxiaoyao.lang</groupId>
8 8
     <artifactId>lang-utils</artifactId>
9 9
     <packaging>pom</packaging>
10
-    <version>1.0.0</version>
10
+    <version>2.0.0</version>
11
+
11 12
     <modules>
12 13
         <module>configuration-loader</module>
13 14
         <module>log-setter</module>