路泰机电科技体检——数据平台后端
zhaowenxuan
2025-05-19 2b97a88ceb6e9d44505b8bfa64fe6ec79ea35166
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
package com.example.config;
 
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import com.example.datasource.DynamicDataSource;
import com.example.enums.DataSourceType;
import com.example.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
 
import javax.servlet.*;
import javax.sql.DataSource;
import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
 
/**
 * @Company: 西安路泰科技有限公司
 * @Author: zhaowenxuan
 * @Date: 2024/7/1 10:27
 */
@Slf4j
@Configuration
public class DruidConfig {
    @Autowired
    private ConfigValue configValue;
 
    private DruidDataSource dataSource;
 
    @Bean
    public DataSource masterDataSource(DruidProperties druidProperties){
        dataSource = DruidDataSourceBuilder.create().build();
        Map<String, String> configMap = configValue.getConfigMap();
        try {
            // 获取属性值并赋值
            Properties properties = new Properties();
            // 这里是测试写法,具体的value可以通过请求参数传递过来
            properties.setProperty("druid.url","jdbc:mysql://"+configMap.get("ip")+":"+configMap.get("prot")+"/"+configMap.get("name")+"" +
                    "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");
            properties.setProperty("druid.username",configMap.get("username"));
            properties.setProperty("druid.password",configMap.get("password"));
            dataSource.restart(properties);
            log.info("数据库连接成功!!!");
        } catch (Exception e) {
            log.error("数据库连接失败  请联系管理员!");
            e.printStackTrace();
        }
        return druidProperties.dataSource(dataSource);
    }
 
    @Bean
//    @ConfigurationProperties("spring.datasource.druid.slavehis")
//    @ConditionalOnProperty(prefix = "spring.datasource.druid.slavehis", name = "enabled", havingValue = "true")
    public DataSource slaveHisDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        Map<String, String> configMap = configValue.getConfigMap();
        // 获取属性值并赋值
        Properties properties = new Properties();
        // 这里是测试写法,具体的value可以通过请求参数传递过来
        properties.setProperty("druid.enabled",configMap.get("hisenabled"));
        properties.setProperty("druid.driverClassName","com.microsoft.sqlserver.jdbc.SQLServerDriver");
        properties.setProperty("druid.url","jdbc:sqlserver://"+configMap.get("hisip")+":"+configMap.get("hisprot")+";DatabaseName="+configMap.get("hisname")+
                ";&characterEncoding=utf8");
        properties.setProperty("druid.username",configMap.get("hisusername"));
        properties.setProperty("druid.password",configMap.get("hispassword"));
        try {
            dataSource.restart(properties);
            log.info("his数据库连接成功!!!");
        } catch (SQLException e) {
            log.error("his数据库连接失败!!!");
        }
        return druidProperties.dataSource(dataSource);
    }
 
    @Bean
//    @ConfigurationProperties("spring.datasource.druid.slavelis")
//    @ConditionalOnProperty(prefix = "spring.datasource.druid.slavelis", name = "enabled", havingValue = "true")
    public DataSource slaveDataLisSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        Map<String, String> configMap = configValue.getConfigMap();
        try {
            // 获取属性值并赋值
            Properties properties = new Properties();
            // 这里是测试写法,具体的value可以通过请求参数传递过来
            properties.setProperty("druid.enabled",configMap.get("lisenabled"));
            properties.setProperty("druid.url","jdbc:mysql://"+configMap.get("lisip")+":"+configMap.get("lisprot")+"/"+configMap.get("lisname")+"" +
                    "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8");
            properties.setProperty("druid.username",configMap.get("lisusername"));
            properties.setProperty("druid.password",configMap.get("lispassword"));
            dataSource.restart(properties);
            log.info("数据库连接成功!!!");
        } catch (Exception e) {
            log.error("数据库连接失败  请联系管理员!");
            e.printStackTrace();
        }
        return druidProperties.dataSource(dataSource);
    }
 
    @Bean
//    @ConfigurationProperties("spring.datasource.druid.slavepacs")
//    @ConditionalOnProperty(prefix = "spring.datasource.druid.slavepacs", name = "enabled", havingValue = "true")
    public DataSource slaveDataPacsSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        Map<String, String> configMap = configValue.getConfigMap();
        try {
            // 获取属性值并赋值
            Properties properties = new Properties();
            // 这里是测试写法,具体的value可以通过请求参数传递过来
            properties.setProperty("druid.enabled",configMap.get("pacsenabled"));
            properties.setProperty("druid.driverClassName","oracle.jdbc.OracleDriver");
            properties.setProperty("druid.url","jdbc:oracle:thin:@//"+configMap.get("pacsip")+"/"+configMap.get("pacsname"));
            properties.setProperty("druid.username",configMap.get("pacsusername"));
            properties.setProperty("druid.password",configMap.get("pacspassword"));
            dataSource.restart(properties);
            log.info("数据库连接成功!!!");
        } catch (Exception e) {
            log.info("数据库连接失败  请联系管理员!");
            e.printStackTrace();
        }
        return druidProperties.dataSource(dataSource);
    }
 
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        setDataSource(targetDataSources, DataSourceType.SLAVE_HIS.name(), "slaveHisDataSource");
        setDataSource(targetDataSources, DataSourceType.SLAVE_LIS.name(), "slaveDataLisSource");
        setDataSource(targetDataSources, DataSourceType.SLAVE_PACS.name(), "slaveDataPacsSource");
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
 
    /**
     * 设置数据源
     *
     * @param targetDataSources 备选数据源集合
     * @param sourceName        数据源名称
     * @param beanName          bean名称
     */
    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName) {
        try {
            DataSource dataSource = SpringUtils.getBean(beanName);
            targetDataSources.put(sourceName, dataSource);
        } catch (Exception e) {
        }
    }
 
    /**
     * 去除监控页面底部的广告
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
    public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) {
        // 获取web监控页面的参数
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取common.js的配置路径
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        // 创建filter进行过滤
        Filter filter = new Filter() {
            @Override
            public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
            }
 
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException {
                chain.doFilter(request, response);
                // 重置缓冲区,响应头不会被重置
                response.resetBuffer();
                // 获取common.js
                String text = Utils.readFromResource(filePath);
                // 正则替换banner, 除去底部的广告信息
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }
 
            @Override
            public void destroy() {
            }
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }
 
    public void changeDataSource(Properties properties) throws SQLException {
        dataSource.restart(properties);
    }
}