Springboot+Mybatis+Druid多数据源配置

1. 新建Springboot项目

Springboot+Mybatis+Druid多数据源配置_第1张图片
Springboot+Mybatis+Druid多数据源配置_第2张图片
根据实际填写
Springboot+Mybatis+Druid多数据源配置_第3张图片
依赖选择Mysql,Mybatis,其他根据实际需要自行选择(此处可不选,接下载可以自己在pom文件中添加):
Springboot+Mybatis+Druid多数据源配置_第4张图片
选择项目路径,然后点击完成
Springboot+Mybatis+Druid多数据源配置_第5张图片
设置项目结构:
Springboot+Mybatis+Druid多数据源配置_第6张图片
Springboot+Mybatis+Druid多数据源配置_第7张图片
将配置文件后缀名该成yml,根据个人习惯,可不改呦
Springboot+Mybatis+Druid多数据源配置_第8张图片
新建config,controller,mapper等目录,结构如下:
Springboot+Mybatis+Druid多数据源配置_第9张图片
启动项目,创建成功
Springboot+Mybatis+Druid多数据源配置_第10张图片

2. 配置多数据源

添加Druid依赖:

		
        
            com.alibaba
            druid
            1.0.18
        

添加application.yml配置信息

server:
  port: 8080

spring:
  # DataSource settings
  datasource:
    db1:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true
      username: test
      password: test
      #连接池的配置信息
      # 初始化大小,最小,最大
      initialSize: 5
      minIdle: 5
      maxActive: 10
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      # 合并多个DruidDataSource的监控数据
      #useGlobalDataSourceStat: true

    db2:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true
      username: test
      password: test
      #连接池的配置信息
      # 初始化大小,最小,最大
      initialSize: 5
      minIdle: 5
      maxActive: 10
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      # 合并多个DruidDataSource的监控数据
      #useGlobalDataSourceStat: true

说明:
1.test1和test2分别是两个本地数据库,库test1中有表user1,库test2中有表user2
2.Druid相关的配置说明信息参照git:https://github.com/alibaba/druid

多数据源配置类

package com.example.multidatasource.config;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author Lee
 * @Description 多数据源配置
 * @Date 2019/12/23 16:14
 * @Version 1.0
 */

@Slf4j
@Configuration
public class MultiDatasourceConfig {
    // 读取配置文件
    @Bean("db1conf")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public MultiDatasourceConfig.DataSourceSetting statisticsConf() {
        return new MultiDatasourceConfig.DataSourceSetting();
    }

    // 读取配置文件
    @Bean("db2conf")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public MultiDatasourceConfig.DataSourceSetting transitConf() {
        return new MultiDatasourceConfig.DataSourceSetting();
    }

    private DataSource config(MultiDatasourceConfig.DataSourceSetting dss) {
        log.info("Initiating DataSource ...");
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dss.getUrl());
        datasource.setUsername(dss.getUsername());
        datasource.setPassword(dss.getPassword());
        datasource.setDriverClassName(dss.getDriverClassName());
        //configuration
        datasource.setInitialSize(dss.getInitialSize());
        datasource.setMinIdle(dss.getMinIdle());
        datasource.setMaxActive(dss.getMaxActive());
        datasource.setMaxWait(dss.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(dss.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(dss.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(dss.getValidationQuery());
        datasource.setTestWhileIdle(dss.isTestWhileIdle());
        datasource.setTestOnBorrow(dss.isTestOnBorrow());
        datasource.setTestOnReturn(dss.isTestOnReturn());
        datasource.setPoolPreparedStatements(dss.isPoolPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(dss.getMaxPoolPreparedStatementPerConnectionSize());
        try {
            datasource.setFilters(dss.getFilters());
        } catch (SQLException e) {
            log.error("druid configuration initialization filter: ", e);
        }
        datasource.setConnectionProperties(dss.getConnectionProperties());
        // 支持多行语句
        List proxyFilters = datasource.getProxyFilters();
        for (Filter proxyFilter : proxyFilters) {
            if (proxyFilter instanceof WallFilter) {
                WallConfig config = ((WallFilter) proxyFilter).getConfig();
                if (config == null) {
                    config = new WallConfig();
                }
                config.setMultiStatementAllow(true);
                ((WallFilter) proxyFilter).setConfig(config);
            }
        }
        return datasource;
    }

    @Bean(name = "db1")
    public DataSource mysql(@Qualifier("db1conf") MultiDatasourceConfig.DataSourceSetting dss) {
        return config(dss);
    }

    @Bean(name = "db2")
    public DataSource oracle2(@Qualifier("db2conf") MultiDatasourceConfig.DataSourceSetting dss) {
        return config(dss);
    }


    @Bean
    public ServletRegistrationBean druidServlet() {
        log.info("Initiating Druid Servlet Configurations ...");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP白名单
        servletRegistrationBean.addInitParameter("allow", "192.168.2.25,127.0.0.1");
        // IP黑名单(共同存在时,deny优先于allow)
        servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }


    @Data
    protected class DataSourceSetting {
        private String  url;
        private String  username;
        private String  password;
        private String  driverClassName;
        private int     initialSize;
        private int     minIdle;
        private int     maxActive;
        private int     maxWait;
        private int     timeBetweenEvictionRunsMillis;
        private int     minEvictableIdleTimeMillis;
        private String  validationQuery;
        private boolean testWhileIdle;
        private boolean testOnBorrow;
        private boolean testOnReturn;
        private boolean poolPreparedStatements;
        private int     maxPoolPreparedStatementPerConnectionSize;
        private String  filters;
        private String  connectionProperties;
    }
}

数据库1配置类

package com.example.multidatasource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @Author Lee
 * @Description 数据库1配置类
 * @Date 2019/12/23 16:06
 * @Version 1.0
 */

@Configuration
@MapperScan(value = "com.example.multidatasource.mappers.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")
public class MultiMybatisDb1Config {

    private final DataSource ds;

    @Autowired
    public MultiMybatisDb1Config(@Qualifier("db1") DataSource ds) {
        this.ds = ds;
    }

    @Bean
    public SqlSessionFactory db1SqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds); // 连接mysql
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate statisticsSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(db1SqlSessionFactory());
    }
}

数据库2配置类

package com.example.multidatasource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @Author Lee
 * @Description 数据库2配置类
 * @Date 2019/12/23 16:18
 * @Version 1.0
 */

@Configuration
@MapperScan(value = "com.example.multidatasource.mappers.db2", sqlSessionFactoryRef = "db2SqlSessionFactory")
public class MultiMybatisDb2Config {

    private final DataSource ds;

    @Autowired
    public MultiMybatisDb2Config(@Qualifier("db2") DataSource ds) {
        this.ds = ds;
    }

    @Bean
    public SqlSessionFactory db2SqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds); // 连接mysql
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate db2SqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(db2SqlSessionFactory());
    }
}

Controller类

package com.example.multidatasource.controller;

import com.example.multidatasource.mapper.db1.TestMapper1;
import com.example.multidatasource.mapper.db2.TestMapper2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author Lee
 * @Description 测试Controller
 * @Date 2019/12/23 16:26
 * @Version 1.0
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private TestMapper1 mapper1;

    @Autowired
    private TestMapper2 mapper2;

    @GetMapping("/user1")
    public Object getUser1(){
        return mapper1.test();
    }

    @GetMapping("/user2")
    public Object getUser2(){
        return mapper2.test();
    }
}

mapper1类

package com.example.multidatasource.mapper.db1;

import org.apache.ibatis.annotations.Select;

import java.util.Map;

/**
 * @Author Lee
 * @Description 多数据源测试1
 * @Date 2019/12/23 16:21
 * @Version 1.0
 */
public interface TestMapper1 {

    @Select("select * from user1")
    Map test();
}

mapper2类

package com.example.multidatasource.mapper.db2;

import org.apache.ibatis.annotations.Select;

import java.util.Map;

/**
 * @Author Lee
 * @Description 测试2
 * @Date 2019/12/23 16:21
 * @Version 1.0
 */
public interface TestMapper2 {
    @Select("select * from user2")
    Map test();
}

运行程序

测试:
Springboot+Mybatis+Druid多数据源配置_第11张图片
Springboot+Mybatis+Druid多数据源配置_第12张图片
登陆监控页面地址:http://localhost:8080/druid
需要登录,用户名密码配置在多数据源配置类
Springboot+Mybatis+Druid多数据源配置_第13张图片
登录成功后界面如下Springboot+Mybatis+Druid多数据源配置_第14张图片

简要记录下,有不足之处,尽请拍砖

你可能感兴趣的:(Druid,Mysql,数据库)