Druid自定义Filter实现

参考:https://github.com/alibaba/druid/blob/master/src/main/java/com/alibaba/druid/filter/config/ConfigFilter.java

新建配置文件:META-INF/druid-filter.properties

1
druid.filters.myfilter=cn.appblog.mall.dao.filter.FilterAdapter
1
2
3
4
5
6
7
8
9
10
spring:
datasource:
appblog:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.1.10:3306/appblog?useUnicode=true&autoReconnect=true&characterEncoding=utf-8
username: appblog
password: Up58k0xJr7C2kcVFTGrnxRlyPBsj7DPeKjMYUAHxWQfjighJLheMrDIlp7Xj8r5Ad1I8Q+qh5WwnCv5kFyWlTQ==
filters: config,myfilter
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=3000;config.decrypt=true;config.decrypt.key=MFwwDQYJKoZIhvcNa5EBkQADSwAwSAJ6ALYHjdmAVAm79Ao3MbruNxsWM76Ifz+qaN8sOZesMKvYCJdpxLFLtmo6bNkpYkzk+OAYhXf7U8r0+dZngOy0RnMCAwEAAQ==
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
@Slf4j
@Component
public class MyDruidFilter extends FilterAdapter {

@Override
public void init(DataSourceProxy dataSourceProxy) {
if (!(dataSourceProxy instanceof DruidDataSource)) {
log.error("ConfigLoader only support DruidDataSource");
}
DruidDataSource dataSource = (DruidDataSource) dataSourceProxy;
log.info("db configuration: url=" + dataSource.getUrl());

Properties properties = dataSource.getConnectProperties();
String password = dataSource.getPassword();
log.info("password: {}", password);
try {
PublicKey publicKey = getPublicKey(properties);
password = ConfigTools.decrypt(publicKey, password);
log.info("password: {}", password);
} catch (Exception e) {
log.warn("DataSource password decrypt error.", e);
}
//dataSource.setPassword(password);
try {
// 将信息配置进Druid
DruidDataSourceFactory.config(dataSource, properties);
} catch (Exception e) {
log.error("DataSource config error.", e);
}
}

@Override
public ConnectionProxy connection_connect(FilterChain chain, Properties info) throws SQLException {
DruidDataSource dataSource = (DruidDataSource) chain.getDataSource();
if (dataSource.isInited()) {

}
return super.connection_connect(chain, info);
}

public PublicKey getPublicKey(Properties connectionProperties) {
String key = connectionProperties.getProperty("config.decrypt.key");
log.info("config.decrypt.key: {}", key);

if (StringUtils.isEmpty(key)) {
key = System.getProperty("druid.config.decrypt.key");
log.info("druid.config.decrypt.key: {}", key);
}

return ConfigTools.getPublicKey(key);
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :