jiazx0107@163.com
2023-05-17 620eab6cca2bc9ef9ea6d3067a0a5ba1deadbd1c
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
package com.ld.igds.conf;
 
import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.ld.igds.constant.DataSourceEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
 
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 配置Mybatis-plus和数据源,系统默认数据源为:db-sys
 *
 * @author Andy
 */
@Configuration
@MapperScan(basePackages = {"com.ld.igds.*.mapper"})
public class MyBatisPlusConf {
 
    public static final String BEAN_DB_BASE = "db-base";
 
    public static final String BEAN_DB_SQLITE = "db-sqlite";
 
    public static final String BEAN_SQL_SESSION_FACTORY = "sqlSessionFactory";
 
    public static final String BEAN_JDBC_TEMPLETE_SQLITE = "sqliteJdbcTemplete";
 
 
    /**
     * 数据库连接密码默认加密KEY,配置文件里面可以不配置
     */
    public static String DEFAULT_PUBLIC_KEY_STRING = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMyIfMDTpJ2HQUOqPxNW4WWuqg0uPVEAiWUqmZ4sFvklLQhJeMURcTGjT9wcKW1vfYeiilanzKWaT+fhnm5FqhcCAwEAAQ==";
    public static String DEFAULT_PRIVATE_KEY_STRING = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAzIh8wNOknYdBQ6o/E1bhZa6qDS49UQCJZSqZniwW+SUtCEl4xRFxMaNP3BwpbW99h6KKVqfMpZpP5+GebkWqFwIDAQABAkEAr2Mixx81e7et6V4ltGm94jnCrIbIIZu6Nbwv+oiIMp95oBATuQtGOJsR/AMeK3QFjzZDOxa3miyRl8hOSG0ysQIhAP7ygMG46DlqXCHykAbBXpC6lH4Opr5JbwF1+Hlesl/1AiEAzWCxcDUG3XAVUr3gBC0bwMEoPTMDcJ+WT9+tHUuUllsCIQDh6k5CW/Icfq1pv6H0+oErysou8hi74iKlrr4h/tIdyQIgEdswUjMqD6KpF/KOQY6ydQXWO8vtpqMZbIRkBsIFfzUCIBsUXMa0vJvtrwhc23ranm7vd9bLW1hyKhOIPU1njxi6";
 
    @Autowired
    private BaseDataSourceProperties properties;
 
 
    @Value("${mybatis-plus.mapper-locations}")
    private String mapperLocations;
    @Value("${mybatis-plus.typeAliasesPackage}")
    private String typeAliasesPackage;
 
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLocalPage(true);
        paginationInterceptor.setDialectType(DbType.MYSQL.getValue());
        return paginationInterceptor;
    }
 
    /**
     * SQL执行效率插件 设置 dev uat 环境开启
     */
    @Bean
    @Profile({"dev", "uat"})
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(1000);
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }
 
    // ---------------数据源的配置 ===================//
 
//    @Bean(name = BEAN_DB_BASE)
//    @ConfigurationProperties(prefix = "spring.datasource.db-base")
//    public DataSource dbBase() {
//        return DruidDataSourceBuilder.create().build();
//    }
 
    @Bean(name = BEAN_DB_BASE)
    public DataSource dbBase() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getDriverClassName());
        druidDataSource.setUrl(properties.getUrl());
        druidDataSource.setUsername(properties.getUsername());
        druidDataSource.setPassword(properties.getPassword());
        druidDataSource.setInitialSize(properties.getInitialSize());
        druidDataSource.setMinIdle(properties.getMinIdle());
        druidDataSource.setMaxActive(properties.getMaxActive());
        druidDataSource.setMaxWait(properties.getMaxWait());
        druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
        druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
        druidDataSource.setValidationQuery(properties.getValidationQuery());
        druidDataSource.setTestWhileIdle(properties.isTestWhileIdle());
        druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
        druidDataSource.setTestOnReturn(properties.isTestOnReturn());
        druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
        druidDataSource.setRemoveAbandoned(properties.isRemoveAbandoned());
        druidDataSource.setRemoveAbandonedTimeout(properties.getRemoveAbandonedTimeout());
        druidDataSource.setLogAbandoned(properties.isLogAbandoned());
        //是否启用密文
        try {
            if (properties.isConfigDecrypt()) {
                String publicKey = properties.getPublicKey();
                if (StringUtils.isEmpty(publicKey)) {
                    publicKey = DEFAULT_PUBLIC_KEY_STRING;
                }
                String password = properties.getPassword();
                String dbpassword = ConfigTools.decrypt(publicKey, password);
                druidDataSource.setPassword(dbpassword);
            }
            druidDataSource.setConnectProperties(properties.getConnectionProperties());
            druidDataSource.setFilters(properties.getFilters());
            druidDataSource.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return druidDataSource;
    }
 
    @Bean(name = BEAN_DB_SQLITE)
    @ConfigurationProperties(prefix = "spring.datasource.db-sqlite")
    public DataSource dbSqlite() {
        return DruidDataSourceBuilder.create().build();
    }
 
    @Bean
    @Primary
    public DataSource multipleDataSource(@Qualifier(BEAN_DB_BASE) DataSource dbBase,
                                         @Qualifier(BEAN_DB_SQLITE) DataSource dbSqlite) {
        MultipleDataSource multipleDataSource = new MultipleDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceEnum.DB_BASE.getValue(), dbBase);
        targetDataSources.put(DataSourceEnum.DB_SQLITE.getValue(), dbSqlite);
 
        // 添加数据源
        multipleDataSource.setTargetDataSources(targetDataSources);
 
        // 设置默认数据源
        multipleDataSource.setDefaultTargetDataSource(dbBase);
 
        return multipleDataSource;
    }
 
    @Bean(name = BEAN_SQL_SESSION_FACTORY)
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(multipleDataSource(dbBase(), dbSqlite()));
 
        //配置mybatis
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        sqlSessionFactory.setTypeAliasesPackage(typeAliasesPackage);
 
        MybatisConfiguration configuration = new MybatisConfiguration();
 
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        sqlSessionFactory.setConfiguration(configuration);
 
        //添加分页支持
        sqlSessionFactory.setPlugins(new Interceptor[]{
                paginationInterceptor()
        });
 
        // sqlSessionFactory.setGlobalConfig(globalConfiguration());
        return sqlSessionFactory.getObject();
    }
 
 
    @Bean(name = BEAN_JDBC_TEMPLETE_SQLITE)
    public JdbcTemplate sqliteJdbcTemplete(
            @Qualifier(BEAN_DB_SQLITE) DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
 
 
    /**
     * 说明,请注意:当前方法使用后,禁止保留密码明文
     *
     * @param args
     */
    public static void main(String[] args) {
        try {
            String password = "";
            System.out.println("明文密码: " + password);
            //私钥
            String privateKey = DEFAULT_PRIVATE_KEY_STRING;
            //公钥
            String publicKey = DEFAULT_PUBLIC_KEY_STRING;
 
            //用私钥加密后的密文
            password = ConfigTools.encrypt(privateKey, password);
 
            System.out.println("密文密码:" + password);
 
            String decryptPassword = ConfigTools.decrypt(publicKey, password);
            System.out.println("解密后:" + decryptPassword);
 
        } catch (Exception e) {
 
        }
    }
 
 
}