# SQL_SERVER
spring:
datasource:
#使用druid配置多数据源,此处配置了两个数据源
druid:
one:
driver-class-name: net.sourceforge.jtds.jdbc.Driver
url: jdbc:jtds:sqlserver://192.168.40.48:1433/HY_MIOT
username: sa
password: Admin2012
#连接超时时间
max-wait: 60000
#初始化连接数
initial-size: 5
validation-query: select 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
#配置监控统计拦截的filters
filters: stat
#最大连接数
max-active: 20
#最小连接数
min-idle: 3
#连接在池中的最小生成时间,单位毫秒
min-evictable-idle-time-millis: 300000
#配置检测需要关闭的空闲连接的间隔时间,单位毫秒
time-between-eviction-runs-millis: 60000
#以下两个是关闭druid连接发生异常时自动重连功能
connection-error-retry-attempts: 0
break-after-acquire-failure: true
two:
driver-class-name: net.sourceforge.jtds.jdbc.Driver
url: jdbc:jtds:sqlserver://192.168.40.48:1433/qsb_test
username: sa
password: Admin2012
max-wait: 60000
initial-size: 5
validation-query: select 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
filters: stat
max-active: 20
min-idle: 3
min-evictable-idle-time-millis: 300000
time-between-eviction-runs-millis: 60000
/**
* druid配置
*/
@Configuration
public class DruidConfiguration {
@Primary
@Bean
@ConfigurationProperties("spring.datasource.druid.one")
public DataSource dataSourceOne() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.two")
public DataSource dataSourceTwo() {
return DruidDataSourceBuilder.create().build();
}
@Bean
public StatFilter stateFilter() {
StatFilter statFilter = new StatFilter();
//是否记录慢sql
statFilter.setLogSlowSql(true);
//慢sql定义的查询时间,单位毫秒
statFilter.setSlowSqlMillis(10000);
return statFilter;
}
}
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>qsb-dtcontextName>
<property name="log.path" value="./log" />
<property name="CONSOLE_LOG_PATTERN"
value="%date{yyyy-MM-dd HH:mm:ss} | %highlight(%-5level) | %boldYellow(%thread) | %boldGreen(%logger) | %msg%n"/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${CONSOLE_LOG_PATTERN}pattern>
layout>
appender>
<appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERRORlevel>
<onMatch>DENYonMatch>
<onMismatch>ACCEPTonMismatch>
filter>
<File>${log.path}/dt-info.logFile>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/dt-info.%d{yyyy-MM-dd}.logfileNamePattern>
<maxHistory>90maxHistory>
rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%npattern>
encoder>
appender>
<appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>Errorlevel>
filter>
<File>${log.path}/dt-error.logFile>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.path}/dt-error.%d{yyyy-MM-dd}.logFileNamePattern>
<maxHistory>90maxHistory>
rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%npattern>
encoder>
appender>
<root level="info">
<appender-ref ref="console" />
<appender-ref ref="fileInfoLog" />
<appender-ref ref="fileErrorLog" />
root>
configuration>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<optional>trueoptional>
dependency>
修改idea build project automatically (勾选)
file->settings->build,execution,deployment -> compile
alt+shift+ctrl+/ 设置register (勾选)
compiler.automake.allow.when.app.running
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
@Lazy(false)
public class ApplicationContextRegister implements ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextRegister.class);
private static ApplicationContext APPLICATION_CONTEXT;
/** * 设置spring上下文 * * @param applicationContext spring上下文 * @throws BeansException */
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
LOGGER.debug("ApplicationContext registed-->{}", applicationContext); APPLICATION_CONTEXT = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return APPLICATION_CONTEXT;
}
}
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:jtds:sqlserver://192.168.40.1:1433/ds
driver-class-name: net.sourceforge.jtds.jdbc.Driver
username: sa
password: xxx
application:
name: qsb-dt
# 更多数据源
custom:
datasource:
names: ds1,ds2
ds1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: net.sourceforge.jtds.jdbc.Driver
url: jdbc:jtds:sqlserver://192.168.40.1:1433/ds1
username: sa
password: xxx
ds2:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: net.sourceforge.jtds.jdbc.Driver
url: jdbc:jtds:sqlserver://192.168.40.1:1433/ds2
username: sa
password: xxx
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 其实springboot已经集成了一个切换多数据源的方法,AbstractRoutingDataSource
* 可以理解为一个map,它的key是数据源的名称,可以自己定义,它的value就是对应
* 的数据源,底层的切换不需要关心,只需要告诉
/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
import java.util.ArrayList;
import java.util.List;
/**
* 这是动态数据员的实际切换类。底层的切换不需要关心,只需要告诉需要的数据源
* 的name就可以了。这边的保持当前数据源的name用的是ThreadLocal,为的是线程安
* 全,保障线程安全。
*/
public class DynamicDataSourceContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal();
public static List dataSourceIds = new ArrayList<>();
//切换数据源的方法
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getDataSourceType() {
return contextHolder.get();
}
public static void clearDataSourceType() {
contextHolder.remove();
}
/**
* 判断指定DataSrouce当前是否存在
*
* @param dataSourceId
*/
public static boolean containsDataSource(String dataSourceId){
return dataSourceIds.contains(dataSourceId);
}
}
/**
* 动态数据源注册
* 启动动态数据源请在启动类中(如SpringBootSampleApplication)
* 添加 @Import(DynamicDataSourceRegister.class)
*
*/
public class DynamicDataSourceRegister
implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);
private ConversionService conversionService = new DefaultConversionService();
private PropertyValues dataSourcePropertyValues;
// 如配置文件中未指定数据源类型,使用该默认值
private static final Object DATASOURCE_TYPE_DEFAULT = "org.apache.tomcat.jdbc.pool.DataSource";
// private static final Object DATASOURCE_TYPE_DEFAULT =
// "com.zaxxer.hikari.HikariDataSource";
// 数据源
private DataSource defaultDataSource;
private Map customDataSources = new HashMap<>();
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map
import java.lang.annotation.*;
/**
* 在方法上使用,用于指定使用哪个数据源
*
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String name();
}
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
@Before("@annotation(ds)")
public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
String dsId = ds.name();
if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
logger.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature());
} else {
logger.debug("Use DataSource : {} > {}", ds.name(), point.getSignature());
DynamicDataSourceContextHolder.setDataSourceType(ds.name());
}
}
@After("@annotation(ds)")
public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
@Service
public class TestService {
@Autowired private BdPersonMapper bdPersonMapper;
/**
* 指定数据源
*/
@TargetDataSource(name="ds1")
public List findAll1(){
return bdPersonMapper.findAll();
}
/**
* 指定数据源
*/
@TargetDataSource(name="ds2")
public List findAll2(){
return bdPersonMapper.findAll();
}
}