测试用户
2023-04-13 43393f2bb11cbf9e6af40077bbc5284660e8a754
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package com;
 
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.druid.wall.WallFilter;
import com.alibaba.fastjson.JSONObject;
import com.common.annotation.JfinalModelScan;
import com.common.annotation.Table;
import com.common.component.DruidPlugin;
import com.common.component.RedisCache;
import com.common.configure.JfinalProperties;
import com.common.core.utils.KitClassUtils;
import com.common.core.utils.SecretsManagerUtils;
import com.common.core.utils.SpringContextUtils;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.IContainerFactory;
import com.jfinal.plugin.activerecord.cache.ICache;
import com.jfinal.plugin.activerecord.dialect.*;
import com.jfinal.template.source.StringSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
 
 
/**
 * @author 廖振钦
 * @Date 2022-01-11 10:24
 * */
 
@Slf4j
@Configuration
@SpringBootApplication(exclude ={DataSourceAutoConfiguration.class} )
@JfinalModelScan(basePackages = {"com.deloitte"})
@EnableAsync
@EnableScheduling // 开启定时任务功能
public class Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        log.info("(♥◠‿◠)ノ゙  系统启动成功   ლ(´ڡ`ლ)゙  \n");
        log.info("swagger文档地址  http://"+getHost()+":"+SpringContextUtils.getEnvParam("server.port")+SpringContextUtils.getEnvParam("server.servlet.context-path")+"/doc.html");
    }
 
    public static String getHost(){
        try {
            InetAddress addr = InetAddress.getLocalHost();
            return addr.getHostAddress();
        } catch (UnknownHostException e) {
            log.error("启动失败",e);
        }
        return "";
    }
 
 
    private Map<DatabaseDriver, Dialect> dialectMap = new HashMap<>();
 
    @Autowired
    private Environment env;
 
    @Autowired
    private JfinalProperties jfinalProperties;
 
    @Autowired
    private SecretsManagerUtils secretsManagerUtils;
 
    @Bean
    public DruidPlugin getDruidPlugin(){
        System.setProperty("druid.mysql.usePingMethod", "false");
        JSONObject object = secretsManagerUtils.getSecret(env.getProperty("aws.secrets.mysql"));
        String port = object.getString("port");
        String host = object.getString("host");
        String dbname = object.getString("dbname");
        String username = object.getString("username");
        String password = object.getString("password");
        String url = "jdbc:mysql://" + host + ":" + port + "/" + dbname + "?characterEncoding=utf8&useSSL=true&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&useUnicode=true&serverTimezone=Asia/Shanghai";
        DruidPlugin dbPlugin=new DruidPlugin(url , username, password);
        // 配置防火墙加强数据库安全
        WallFilter wallFilter = new WallFilter();
        wallFilter.setDbType(JdbcConstants.MYSQL);
        dbPlugin.addFilter(wallFilter);
 
        //配置监控
        StatFilter statFilter=new StatFilter();
        statFilter.setMergeSql(true);
        statFilter.setLogSlowSql(true);
        statFilter.setSlowSqlMillis(1500);
 
        // 添加 StatFilter 才会有统计数据
        dbPlugin.addFilter(statFilter);
        dbPlugin.start();
        return dbPlugin;
    }
 
    @Bean
    @ConditionalOnMissingBean(ICache.class)
    @ConditionalOnClass(name = "org.springframework.cache.CacheManager")
    public ICache cache() {
        return SpringContextUtils.getBean(RedisCache.class);
    }
 
    @Bean
    @ConditionalOnMissingBean(IContainerFactory.class)
    public IContainerFactory containerFactory() {
        // 不区分大小写 但是最后字段名统一小写
        return new CaseInsensitiveContainerFactory(true);
    }
 
    @Bean
    public ActiveRecordPlugin activeRecordPlugin(ICache cache,
                                                 DruidPlugin dataSource,
                                      IContainerFactory containerFactory) {
        dialectMap.put(DatabaseDriver.MYSQL, new MysqlDialect());
        dialectMap.put(DatabaseDriver.ORACLE, new OracleDialect());
        dialectMap.put(DatabaseDriver.SQLSERVER, new SqlServerDialect());
        dialectMap.put(DatabaseDriver.SQLITE, new Sqlite3Dialect());
        dialectMap.put(DatabaseDriver.POSTGRESQL, new PostgreSqlDialect());
        ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(dataSource);
        activeRecordPlugin.setCache(cache);
        try {
            DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(dataSource.getDataSource().getConnection().getMetaData().getURL());
            Dialect dialect;
            if (!ObjectUtils.isEmpty(jfinalProperties.getDialect())) {
                dialect = jfinalProperties.getDialect().newInstance();
            } else {
                dialect = dialectMap.get(databaseDriver);
            }
            if (ObjectUtils.isEmpty(dialect)) {
                throw new IllegalArgumentException("dialect not be found!");
            }
            activeRecordPlugin.setDialect(dialect);
        } catch (Exception e) {
            log.error("启动失败",e);
        }
        if (!ObjectUtils.isEmpty(jfinalProperties.getShowSql())) {
            activeRecordPlugin.setShowSql(jfinalProperties.getShowSql());
        }
        if (!ObjectUtils.isEmpty(jfinalProperties.getDevMode())) {
            activeRecordPlugin.setDevMode(jfinalProperties.getDevMode());
        }
        if (!ObjectUtils.isEmpty(jfinalProperties.getTransactionLevel())) {
            activeRecordPlugin.setTransactionLevel(jfinalProperties.getTransactionLevel());
        }
        activeRecordPlugin.setContainerFactory(containerFactory);
        getSqlTemplates(activeRecordPlugin, jfinalProperties.getSqlTemplates());
        getMappingKet(activeRecordPlugin, jfinalProperties.getKitClasses());
        autoMappingTable(activeRecordPlugin);
        activeRecordPlugin.start();
        return activeRecordPlugin;
    }
 
    private void autoMappingTable(ActiveRecordPlugin activeRecordPlugin){
        KitClassUtils.tableclass.forEach(clazz->{
            Table table = (Table)clazz.getAnnotation(Table.class);
            activeRecordPlugin.addMapping(table.tableName(), table.primaryKey(), table.clazz());
        });
    }
 
    private void getSqlTemplates(ActiveRecordPlugin arp, List<String> sqlTemplates) {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList<Resource>();
        if (!ObjectUtils.isEmpty(sqlTemplates)) {
            sqlTemplates.forEach(sqlTemplate -> {
                if (sqlTemplate != null) {
                    try {
                        Resource[] templates = resourceResolver.getResources(sqlTemplate);
                        resources.addAll(Arrays.asList(templates));
                    } catch (IOException e) {
                        log.warn("{} path not found in classpath", sqlTemplate);
                    }
                    resources.forEach(resource -> {
                        StringBuilder content = null;
                        try {
                            content = getContentByStream(resource.getInputStream());
                            arp.addSqlTemplate(new StringSource(content, true));
                        } catch (IOException e) {
                            log.error("启动失败",e);
                        }
                    });
                }
            });
        }
    }
 
    private void getMappingKet(ActiveRecordPlugin activeRecordPlugin, List<String> kitClasses) {
        if (!ObjectUtils.isEmpty(kitClasses)) {
            kitClasses.forEach(kitClass -> {
                try {
                    Class<?> mappingKitClass = Class.forName(kitClass);
                    Object mappingKit = mappingKitClass.newInstance();
                    Method mappingMethod = ReflectionUtils.findMethod(mappingKitClass, "mapping",
                            activeRecordPlugin.getClass());
                    ReflectionUtils.invokeMethod(mappingMethod, mappingKit, activeRecordPlugin);
                } catch (Exception e) {
                    log.warn("{} not found in classpath", kitClass);
                }
            });
        }
    }
 
    private StringBuilder getContentByStream(InputStream inputStream) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception e) {
            log.error("启动失败",e);
        }
        return stringBuilder;
    }
 
}