在Spring-Boot中配置mybatis多数据源

原创
2017/04/28 14:32
阅读数 104

来不及了,直接上代码:D

@Configuration
@EnableConfigurationProperties(DatabaseConfigProperties.class)
@EnableTransactionManagement
public class DatabaseConfig {
    @Autowired
    DatabaseConfigProperties config ;

    @Bean(name="dataSource", initMethod="init",destroyMethod="close")
    @Primary // http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources ,否则spring-boot的DataSourceInitializer在进行数据源初始化时会抛出异常
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(config.getUrl());
        ds.setUsername(config.getUsername());
        ds.setPassword(config.getPassword());
        ds.setInitialSize(ds.getInitialSize());
        ds.setMinIdle(config.getMinIdle());
        ds.setMaxActive(config.getMaxActive());
        ds.setMaxWait(config.getMaxWait());
        ds.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis()); // 关闭检测间隔 毫秒
        ds.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis()); // 一个连接的最小生存时间
        ds.setValidationQuery("SELECT 'x'");
        ds.setTestWhileIdle(config.isTestWhileIdle());
        ds.setTestOnBorrow(config.isTestOnBorrow());
        ds.setTestOnReturn(config.isTestOnReturn());
        ds.setPoolPreparedStatements(config.isPoolPreparedStatements());
        ds.setMaxPoolPreparedStatementPerConnectionSize(config.getMaxPoolPreparedStatementPerConnectionSize());
        ds.setRemoveAbandoned(config.isRemoveAbandoned());
        ds.setRemoveAbandonedTimeout(config.getRemoveAbandonedTimeout());
        ds.setLogAbandoned(config.isLogAbandoned());
        ds.setTimeBetweenLogStatsMillis(config.getTimeBetweenLogStatsMillis());
        ds.setPhyTimeoutMillis(config.getPhyTimeoutMillis());
        ds.setMaxEvictableIdleTimeMillis(config.getMaxEvictableIdleTimeMillis());
        ds.setDbType("mysql");
        try {
            ds.setFilters("stat,slf4j");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ds ;
    }

    @Bean
    public Interceptor[] interceptors(){
        return new Interceptor[]{
            new MybatisInterceptor(),
        };
    }
    @Bean(name="sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        final SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setPlugins(interceptors());
        return factoryBean.getObject();
    }


    @Bean(name="transactionManager")
    PlatformTransactionManager transactionManager(){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource());
        return transactionManager;
    }

    @Bean
    DaoAspect daoAspect(){
      return new DaoAspect();
    }

    @Configuration
    @MapperScan(basePackages="nam.doog.test.dao.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
    public static class MapperConfig{
      // 不能和外部类放在一起配置,否则会导致Mapper找不到正确的sqlSessionFactory
    }
}
@ConfigurationProperties(
    prefix = "jdbc",
    ignoreUnknownFields = false)
public class DatabaseConfigProperties {

  private String url,
      username,
      password,
      validationQuery = "SELECT 'x";
  private int initialSize,
      minIdle,
      maxActive,
      maxWait,
      maxPoolPreparedStatementPerConnectionSize,
      removeAbandonedTimeout;

  private long timeBetweenEvictionRunsMillis,
      minEvictableIdleTimeMillis,
      timeBetweenLogStatsMillis,
      phyTimeoutMillis,
      maxEvictableIdleTimeMillis;

  private boolean testWhileIdle,
      testOnBorrow,
      testOnReturn,
      poolPreparedStatements,
      removeAbandoned,
      logAbandoned;

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getValidationQuery() {
    return validationQuery;
  }

  public void setValidationQuery(String validationQuery) {
    this.validationQuery = validationQuery;
  }

  public int getInitialSize() {
    return initialSize;
  }

  public void setInitialSize(int initialSize) {
    this.initialSize = initialSize;
  }

  public int getMinIdle() {
    return minIdle;
  }

  public void setMinIdle(int minIdle) {
    this.minIdle = minIdle;
  }

  public int getMaxActive() {
    return maxActive;
  }

  public void setMaxActive(int maxActive) {
    this.maxActive = maxActive;
  }

  public int getMaxWait() {
    return maxWait;
  }

  public void setMaxWait(int maxWait) {
    this.maxWait = maxWait;
  }

  public int getMaxPoolPreparedStatementPerConnectionSize() {
    return maxPoolPreparedStatementPerConnectionSize;
  }

  public void setMaxPoolPreparedStatementPerConnectionSize(
      int maxPoolPreparedStatementPerConnectionSize) {
    this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
  }

  public int getRemoveAbandonedTimeout() {
    return removeAbandonedTimeout;
  }

  public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
    this.removeAbandonedTimeout = removeAbandonedTimeout;
  }

  public long getTimeBetweenEvictionRunsMillis() {
    return timeBetweenEvictionRunsMillis;
  }

  public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
    this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  }

  public long getMinEvictableIdleTimeMillis() {
    return minEvictableIdleTimeMillis;
  }

  public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
    this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  }

  public long getTimeBetweenLogStatsMillis() {
    return timeBetweenLogStatsMillis;
  }

  public void setTimeBetweenLogStatsMillis(long timeBetweenLogStatsMillis) {
    this.timeBetweenLogStatsMillis = timeBetweenLogStatsMillis;
  }

  public long getPhyTimeoutMillis() {
    return phyTimeoutMillis;
  }

  public void setPhyTimeoutMillis(long phyTimeoutMillis) {
    this.phyTimeoutMillis = phyTimeoutMillis;
  }

  public long getMaxEvictableIdleTimeMillis() {
    return maxEvictableIdleTimeMillis;
  }

  public void setMaxEvictableIdleTimeMillis(long maxEvictableIdleTimeMillis) {
    this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis;
  }

  public boolean isTestWhileIdle() {
    return testWhileIdle;
  }

  public void setTestWhileIdle(boolean testWhileIdle) {
    this.testWhileIdle = testWhileIdle;
  }

  public boolean isTestOnBorrow() {
    return testOnBorrow;
  }

  public void setTestOnBorrow(boolean testOnBorrow) {
    this.testOnBorrow = testOnBorrow;
  }

  public boolean isTestOnReturn() {
    return testOnReturn;
  }

  public void setTestOnReturn(boolean testOnReturn) {
    this.testOnReturn = testOnReturn;
  }

  public boolean isPoolPreparedStatements() {
    return poolPreparedStatements;
  }

  public void setPoolPreparedStatements(boolean poolPreparedStatements) {
    this.poolPreparedStatements = poolPreparedStatements;
  }

  public boolean isRemoveAbandoned() {
    return removeAbandoned;
  }

  public void setRemoveAbandoned(boolean removeAbandoned) {
    this.removeAbandoned = removeAbandoned;
  }

  public boolean isLogAbandoned() {
    return logAbandoned;
  }

  public void setLogAbandoned(boolean logAbandoned) {
    this.logAbandoned = logAbandoned;
  }

}
@Configuration
@EnableConfigurationProperties(AnotherDatabaseConfigProperties.class)
public class AnotherDatabaseConfig { // 因为不需要事务,所以没有写事务配置,有需要可以加上
    @Autowired
    AnotherDatabaseConfigProperties config ;

    @Bean(name="anotherDataSource", initMethod="init",destroyMethod="close" )
    public DataSource anotherDataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(config.getUrl());
        ds.setUsername(config.getUsername());
        ds.setPassword(config.getPassword());
        ds.setInitialSize(ds.getInitialSize());
        ds.setMinIdle(config.getMinIdle());
        ds.setMaxActive(config.getMaxActive());
        ds.setMaxWait(config.getMaxWait());
        ds.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis()); // 关闭检测间隔 毫秒
        ds.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis()); // 一个连接的最小生存时间
        ds.setValidationQuery("SELECT 'x'");
        ds.setTestWhileIdle(config.isTestWhileIdle());
        ds.setTestOnBorrow(config.isTestOnBorrow());
        ds.setTestOnReturn(config.isTestOnReturn());
        ds.setPoolPreparedStatements(config.isPoolPreparedStatements());
        ds.setMaxPoolPreparedStatementPerConnectionSize(config.getMaxPoolPreparedStatementPerConnectionSize());
        ds.setRemoveAbandoned(config.isRemoveAbandoned());
        ds.setRemoveAbandonedTimeout(config.getRemoveAbandonedTimeout());
        ds.setLogAbandoned(config.isLogAbandoned());
        ds.setTimeBetweenLogStatsMillis(config.getTimeBetweenLogStatsMillis());
        ds.setPhyTimeoutMillis(config.getPhyTimeoutMillis());
        ds.setMaxEvictableIdleTimeMillis(config.getMaxEvictableIdleTimeMillis());
        ds.setDbType("mysql");
        try {
            ds.setFilters("stat,slf4j");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ds ;
    }

    @Bean(name="anotherSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        final SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(anotherDataSource());
        return factoryBean.getObject();
    }

    @Configuration
    @MapperScan(basePackages="nam.doog.test.dao.anothermapper", sqlSessionFactoryRef = "anotherSqlSessionFactory")
    public static class MapperConfig{

    }
}
@ConfigurationProperties(
    prefix = "anotherjdbc",
    ignoreUnknownFields = false)
public class AnotherPayDatabaseConfigProperties {

  private String url,
      username,
      password,
      validationQuery = "SELECT 'x";
  private int initialSize,
      minIdle,
      maxActive,
      maxWait,
      maxPoolPreparedStatementPerConnectionSize,
      removeAbandonedTimeout;

  private long timeBetweenEvictionRunsMillis,
      minEvictableIdleTimeMillis,
      timeBetweenLogStatsMillis,
      phyTimeoutMillis,
      maxEvictableIdleTimeMillis;

  private boolean testWhileIdle,
      testOnBorrow,
      testOnReturn,
      poolPreparedStatements,
      removeAbandoned,
      logAbandoned;

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getValidationQuery() {
    return validationQuery;
  }

  public void setValidationQuery(String validationQuery) {
    this.validationQuery = validationQuery;
  }

  public int getInitialSize() {
    return initialSize;
  }

  public void setInitialSize(int initialSize) {
    this.initialSize = initialSize;
  }

  public int getMinIdle() {
    return minIdle;
  }

  public void setMinIdle(int minIdle) {
    this.minIdle = minIdle;
  }

  public int getMaxActive() {
    return maxActive;
  }

  public void setMaxActive(int maxActive) {
    this.maxActive = maxActive;
  }

  public int getMaxWait() {
    return maxWait;
  }

  public void setMaxWait(int maxWait) {
    this.maxWait = maxWait;
  }

  public int getMaxPoolPreparedStatementPerConnectionSize() {
    return maxPoolPreparedStatementPerConnectionSize;
  }

  public void setMaxPoolPreparedStatementPerConnectionSize(
      int maxPoolPreparedStatementPerConnectionSize) {
    this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
  }

  public int getRemoveAbandonedTimeout() {
    return removeAbandonedTimeout;
  }

  public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
    this.removeAbandonedTimeout = removeAbandonedTimeout;
  }

  public long getTimeBetweenEvictionRunsMillis() {
    return timeBetweenEvictionRunsMillis;
  }

  public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
    this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  }

  public long getMinEvictableIdleTimeMillis() {
    return minEvictableIdleTimeMillis;
  }

  public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
    this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  }

  public long getTimeBetweenLogStatsMillis() {
    return timeBetweenLogStatsMillis;
  }

  public void setTimeBetweenLogStatsMillis(long timeBetweenLogStatsMillis) {
    this.timeBetweenLogStatsMillis = timeBetweenLogStatsMillis;
  }

  public long getPhyTimeoutMillis() {
    return phyTimeoutMillis;
  }

  public void setPhyTimeoutMillis(long phyTimeoutMillis) {
    this.phyTimeoutMillis = phyTimeoutMillis;
  }

  public long getMaxEvictableIdleTimeMillis() {
    return maxEvictableIdleTimeMillis;
  }

  public void setMaxEvictableIdleTimeMillis(long maxEvictableIdleTimeMillis) {
    this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis;
  }

  public boolean isTestWhileIdle() {
    return testWhileIdle;
  }

  public void setTestWhileIdle(boolean testWhileIdle) {
    this.testWhileIdle = testWhileIdle;
  }

  public boolean isTestOnBorrow() {
    return testOnBorrow;
  }

  public void setTestOnBorrow(boolean testOnBorrow) {
    this.testOnBorrow = testOnBorrow;
  }

  public boolean isTestOnReturn() {
    return testOnReturn;
  }

  public void setTestOnReturn(boolean testOnReturn) {
    this.testOnReturn = testOnReturn;
  }

  public boolean isPoolPreparedStatements() {
    return poolPreparedStatements;
  }

  public void setPoolPreparedStatements(boolean poolPreparedStatements) {
    this.poolPreparedStatements = poolPreparedStatements;
  }

  public boolean isRemoveAbandoned() {
    return removeAbandoned;
  }

  public void setRemoveAbandoned(boolean removeAbandoned) {
    this.removeAbandoned = removeAbandoned;
  }

  public boolean isLogAbandoned() {
    return logAbandoned;
  }

  public void setLogAbandoned(boolean logAbandoned) {
    this.logAbandoned = logAbandoned;
  }
}

application.yml:

jdbc:
  url: jdbc:mysql://xxxx/db1?useUnicode=true&characterEncoding=utf8&autoReconnect=true
  username: *****
  password: *****
  initialSize: 5
  minIdle: 10
  maxActive: 100
  maxWait: 60000

  timeBetweenEvictionRunsMillis: 10000
  minEvictableIdleTimeMillis: 40000
  testWhileIdle: true
  testOnBorrow: false
  testOnReturn: false
  poolPreparedStatements: false
  maxPoolPreparedStatementPerConnectionSize: 20
  removeAbandoned: true
  removeAbandonedTimeout: 180
  logAbandoned: true
  timeBetweenLogStatsMillis: 1800000
  phyTimeoutMillis: 100000
  maxEvictableIdleTimeMillis: 100000

anotherjdbc:
  url: jdbc:mysql://xxxx/db2?useUnicode=true&characterEncoding=utf8&autoReconnect=true
  username: *****
  password: *****
  initialSize: 5
  minIdle: 10
  maxActive: 100
  maxWait: 60000

  timeBetweenEvictionRunsMillis: 10000
  minEvictableIdleTimeMillis: 40000
  testWhileIdle: true
  testOnBorrow: false
  testOnReturn: false
  poolPreparedStatements: false
  maxPoolPreparedStatementPerConnectionSize: 20
  removeAbandoned: true
  removeAbandonedTimeout: 180
  logAbandoned: true
  timeBetweenLogStatsMillis: 1800000
  phyTimeoutMillis: 100000
  maxEvictableIdleTimeMillis: 100000
展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部