1、配置数据源
package com.netintech.core.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.netintech.common.core.utils.SpringUtils;
import com.netintech.core.aspectj.lang.enums.DataSourceType;
import com.netintech.core.config.properties.DruidProperties;
import com.netintech.core.datasource.DynamicDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.IOException;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig
{
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource masterDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "slave136DataSource")
@ConfigurationProperties("spring.datasource.druid.slave136")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave136", name = "enabled", havingValue = "true")
public DataSource slave136DataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "slave110DataSource")
@ConfigurationProperties("spring.datasource.druid.slave110")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave110", name = "enabled", havingValue = "true")
public DataSource slave110DataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "slaveGajDataSource")
@ConfigurationProperties("spring.datasource.druid.slavegaj")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slavegaj", name = "enabled", havingValue = "true")
public DataSource slaveGajDataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "slaveZhzx36DataSource")
@ConfigurationProperties("spring.datasource.druid.slavezhzx36")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slavezhzx36", name = "enabled", havingValue = "true")
public DataSource slaveZhzx36DataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "slaveQzdjDataSource")
@ConfigurationProperties("spring.datasource.druid.slaveqzdj")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slaveqzdj", name = "enabled", havingValue = "true")
public DataSource slaveQzdjDataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
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.name(), "slaveDataSource");
setDataSource(targetDataSources, DataSourceType.SLAVE136.name(), "slave136DataSource");
setDataSource(targetDataSources, DataSourceType.SLAVE110.name(), "slave110DataSource");
setDataSource(targetDataSources, DataSourceType.SLAVEGAJ.name(), "slaveGajDataSource");
setDataSource(targetDataSources, DataSourceType.SLAVEZHZX36.name(), "slaveZhzx36DataSource");
setDataSource(targetDataSources, DataSourceType.SLAVEQZDJ.name(), "slaveQzdjDataSource");
return new DynamicDataSource(masterDataSource, targetDataSources);
}
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)
{
DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
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 = 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();
String text = Utils.readFromResource(filePath);
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;
}
}
2、创建枚举类
package com.netintech.core.aspectj.lang.enums;
public enum DataSourceType
{
MASTER,
SLAVE,
SLAVE136,
SLAVE110,
SLAVEGAJ,
SLAVEZHZX36,
SLAVEQZDJ
}
3、创建多数据源切换注解
package com.netintech.core.aspectj.lang.annotation;
import com.netintech.core.aspectj.lang.enums.DataSourceType;
import java.lang.annotation.*;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource
{
public DataSourceType value() default DataSourceType.MASTER;
}
4、数据源注解配置
package com.netintech.core.aspectj;
import com.netintech.common.core.utils.StringUtils;
import com.netintech.core.aspectj.lang.annotation.DataSource;
import com.netintech.core.datasource.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Order(1)
@Component
public class DataSourceAspect
{
protected Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("@annotation(com.netintech.core.aspectj.lang.annotation.DataSource)"
+ "|| @within(com.netintech.core.aspectj.lang.annotation.DataSource)")
public void dsPointCut()
{
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable
{
DataSource dataSource = getDataSource(point);
if (StringUtils.isNotNull(dataSource))
{
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
try
{
return point.proceed();
}
finally
{
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
public DataSource getDataSource(ProceedingJoinPoint point)
{
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
DataSource dataSource = method.getAnnotation(DataSource.class);
Class<? extends Object> targetClass = point.getTarget().getClass();
DataSource targetDataSource = targetClass.getAnnotation(DataSource.class);
if (StringUtils.isNotNull(dataSource))
{
return dataSource;
}
else
{
return targetDataSource;
}
}
}
5、数据库配置
spring:
redis:
host: 172.6.1.1
port: 6379
password: Netma213123rch@2022
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: oracle.jdbc.OracleDriver
druid:
master:
url: jdbc:oracle:thin:@1.1.1.3:1521/zhzx
username: KSSHZL_GD
password: Netma1231rch_2022
slave:
enabled: true
url: jdbc:oracle:thin:@17.1.1.3:1521/zhzx
username: KSSHZL_OPERENTION
password: Netm1231arch_2022
slave136:
enabled: true
url: jdbc:oracle:thin:@17.1.9.1:1521:orcl
username: kssm_141llt
password: kssm_lQWEQlt
slave110:
enabled: true
url: jdbc:oracle:thin:@2.3.3.1:7110:dsdb
username: hxeQEQcs
password: dsdSXADb
slavegaj:
enabled: true
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://2.36.25.162:3306/ks_shzlxdhzhzhzx_push?useUnicode=true&characterEncoding=utf-8&character_set_client=utf8mb4&useSSL=false&serverTimezone=Asia/Shanghai
username: ks_shzlxdhzhzQWEQhzx
password: Ks@Sh231zl!QAZ2wsx
connectionInitSqls: set names utf8mb4;
slavezhzx36:
enabled: true
url: jdbc:oracle:thin:@17.1.19.35:1521/zhzx
username: KSSHZLWEACSZ_GD
password: Netmar1132ch_2022
initialSize: 5
minIdle: 10
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
maxEvictableIdleTimeMillis: 900000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
allow:
url-pattern: /druid/*
login-username:
login-password:
filter:
stat:
enabled: true
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
wall:
config:
multi-statement-allow: true
6、注解切换数据源
package com.netintech.bussiness.mapper.gaj;
import com.netintech.api.domain.operationsystemapplication.workflow.domain.GdJbxxCommon;
import com.netintech.api.domain.operationsystemapplication.workflow.gaj.GajCaseHfResult;
import com.netintech.api.domain.operationsystemapplication.workflow.gaj.GajCaseInfo;
import com.netintech.api.domain.operationsystemapplication.workflow.gaj.GajCaseResult;
import com.netintech.api.domain.operationsystemapplication.workflow.gaj.GajCaseVisit;
import com.netintech.core.aspectj.lang.annotation.DataSource;
import com.netintech.core.aspectj.lang.enums.DataSourceType;
import org.apache.ibatis.annotations.Param;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface GajCaseMapper {
@DataSource(value = DataSourceType.SLAVEZHZX36)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
List<GdJbxxCommon> getCaseInfo();
@DataSource(value = DataSourceType.SLAVEZHZX36)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
List<GdJbxxCommon> getCaseResult(@Param(value = "bjStatus") String bjStatus);
@DataSource(value = DataSourceType.SLAVEZHZX36)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
List<GajCaseHfResult> getCaseVisit();
@DataSource(value = DataSourceType.SLAVEZHZX36)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
int testSlave36();
@DataSource(value = DataSourceType.SLAVE)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
int testSlave();
int testSlave36_2();
@DataSource(value = DataSourceType.SLAVE)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
int updateSlave36();
}