druid使用多个数据源

919 阅读2分钟

于2022/4/7修改

之前写的太烂了,比如没有遵循springboot-druid-start的配置方法放在spring:下只是单纯的映射了文件的信息,datasource的编写也很长,也没有配置druid的监控等等。于是做出修改。

spring:
  datasource:
    druid:
      stat-view-servlet:
        enabled: true                   # 启用StatViewServlet
        url-pattern: /druid/*           # 访问内置监控页面的路径,内置监控页面的首页是/druid/index.html
        reset-enable: false              # 不允许清空统计数据,重新计算
        login-username: root            # 配置监控页面访问密码
        login-password: 123
        allow: 127.0.0.1           # 允许访问的地址,如果allow没有配置或者为空,则允许所有访问
        deny:
      user:
        Driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/cloud_user?serverTimezone=UTC
        username: root
        password: 123456
        #配置初始化大小/最小/最大
        initialSize: 1
        minIdle: 1
        maxActive: 30
        #获取连接等待超时时间
        maxWait: 60000
        #间隔多久进行一次检测,检测需要关闭的空闲连接
        timeBetweenEvictionRunsMillis: 60000
        #一个连接在池中最小生存的时间
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
        poolPreparedStatements: false
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,wall,slf4j
        filter:
          stat:
            merge-sql: true
            slow-sql-millis: 5000
      order:
        Driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/cloud_order?serverTimezone=UTC
        username: root
        password: 123456
        #配置初始化大小/最小/最大
        initialSize: 1
        minIdle: 1
        maxActive: 30
        #获取连接等待超时时间
        maxWait: 60000
        #间隔多久进行一次检测,检测需要关闭的空闲连接
        timeBetweenEvictionRunsMillis: 60000
        #一个连接在池中最小生存的时间
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
        poolPreparedStatements: false
        maxPoolPreparedStatementPerConnectionSize: 20
        # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filters: stat,wall,slf4j
        filter:
          stat:
            merge-sql: true
            slow-sql-millis: 5000

Datasource

@Configuration
public class DataSourceCreate {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.user")
    public DataSource userDataSource() throws SQLException {
        return DruidDataSourceBuilder.create().build();

    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.order")
    public DataSource orderDataSource() {
        DataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }
}

DB1主数据源(@Primary)

@Configuration
@MapperScan(basePackages = UserDataBaseConfig.PACKAGE, sqlSessionFactoryRef = "userSqlSessionFactory", sqlSessionTemplateRef = "userSqlSessionTemplate")
public class UserDataBaseConfig {

    private DataSource userDataSource;
    static final String PACKAGE = "com.example.demo.mapper.user";
    //没用到mapper的xml所以可以不用配置
    //static final String LOCATION = "mapper/user/*xml";

    public UserDataBaseConfig( @Qualifier("userDataSource") DataSource userDataSource){
        this.userDataSource=userDataSource;
    }

    @Bean
    @Primary
    public MybatisSqlSessionFactoryBean userSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(userDataSource);
//        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().
//        getResources(UserDataBaseConfig.LOCATION));
        return sessionFactoryBean;
    }

    @Bean
    @Primary
    public SqlSessionTemplate userSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(userSqlSessionFactory().getObject());
    }
}

DB2

@Configuration
@MapperScan(basePackages = OrderDataBaseConfig.PACKAGE, sqlSessionFactoryRef = "orderSqlSessionFactory", sqlSessionTemplateRef = "orderSqlSessionTemplate")
public class OrderDataBaseConfig {

    private DataSource orderDataSource;
    static final String PACKAGE = "com.example.demo.mapper.order";
    //static final String LOCATION = "mapper/order/*xml";

    public OrderDataBaseConfig(@Qualifier("orderDataSource") DataSource orderDataSource) {
        this.orderDataSource = orderDataSource;

    }

    @Bean
    public MybatisSqlSessionFactoryBean orderSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(orderDataSource);
        //sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().
        // getResources(OrderDataBaseConfig.LOCATION));
        return sessionFactoryBean;
    }

    @Bean
    public SqlSessionTemplate orderSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(orderSqlSessionFactory().getObject());
    }
}

image.png

image.png