SpringBoot集成mybatis使用durid多數據源配置

SpringBoot集成mybatis自定義多數據源配置

1.首先配置application.yml。

因爲spring官方沒有提供和durid集成,所以這部分也需要自定義配置。

datasource:
  local:
    url: jdbc:mysql://127.0.0.1:3306/my_dev?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    driver-class-name: com.mysql.jdbc.Driver
    password: 123456
  remote:
    url: jdbc:mysql://97.64.82.120:3306/my_dev?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    driver-class-name: com.mysql.jdbc.Driver
    password: 123456
  druid:
    #初始化大小,最小,最大
    initial-size: 5
    max-active: 10
    min-idle: 5
    #配置獲取連接等待超時的時間
    max-wait: 6000
    #檢測連接是否有效的sql
    validation-query: "select '1'"
    validation-query-timeout: 2000
    test-on-borrow: false
    test-on-return: false
    test-while-idle: true
    #配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒
    time-between-eviction-runs-millis: 600000
    #配置一個連接在池中最小生存的時間,單位是毫秒
    min-evictable-idle-time-millis: 300000
    remove-abandoned: true

2.Druid基礎配置

用於將yml裏的配置映射進來,屬性名採用駝峯式。

@Getter
@Setter
@ConfigurationProperties(prefix = "datasource.druid")
public class DruidConfigProperties {
    private int initialSize;
    private int maxActive;
    private int minIdle;
    private int maxWait;
    private String validationQuery;
    private int validationQueryTimeout;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean testWhileIdle;
    private long timeBetweenEvictionRunsMillis;
    private long minEvictableIdleTimeMillis;
    private boolean removeAbandoned;
}

3.配置DruidDataSource

@Configuration
@EnableConfigurationProperties(DruidConfigProperties.class)
public class DataSourceConfiguration {

    private final Environment env;
    private final DruidConfigProperties poolProps;


    public DataSourceConfiguration(Environment env, DruidConfigProperties poolProps) {
        this.env = env;
        this.poolProps = poolProps;
    }


    @Bean
    public DataSource localDataSource(){
        DruidDataSource dataSource=createDataSource("local");
        configPool(dataSource,poolProps);
        LOGGER.debug("數據源對象初始化完成->local:{}",dataSource.toString());
        return dataSource;
    }

    @Bean
    public DataSource remoteDataSource(){
        DruidDataSource dataSource=createDataSource("remote");
        configPool(dataSource,poolProps);
        LOGGER.debug("數據源對象初始化完成->remote:{}",dataSource.toString());
        return dataSource;
    }

    //加載durid配置
    private void configPool(DruidDataSource dataSource,DruidConfigProperties poolProps){
        dataSource.setInitialSize(poolProps.getInitialSize());
        dataSource.setMaxActive(poolProps.getMaxActive());
        dataSource.setMinIdle(poolProps.getMinIdle());
        dataSource.setMaxWait(poolProps.getMaxWait());
        dataSource.setMinEvictableIdleTimeMillis(poolProps.getMinEvictableIdleTimeMillis());
        dataSource.setValidationQuery(poolProps.getValidationQuery());
        dataSource.setValidationQueryTimeout(poolProps.getValidationQueryTimeout());
        dataSource.setTestWhileIdle(poolProps.isTestWhileIdle());
        dataSource.setRemoveAbandoned(poolProps.isRemoveAbandoned());
        dataSource.setTestOnBorrow(poolProps.isTestOnBorrow());
        dataSource.setTestOnReturn(poolProps.isTestOnReturn());
    }

    //根據dataSourceName加載對應的數據庫信息
    private DruidDataSource createDataSource(String dataSourceName){
        String template = "datasource.%s.%s";
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty(String.format(template,dataSourceName,"url")));
        dataSource.setUsername(env.getProperty(String.format(template,dataSourceName,"username")));
        dataSource.setPassword(env.getProperty(String.format(template,dataSourceName,"password")));
        dataSource.setDriverClassName(env.getProperty(String.format(template, dataSourceName, "driver-class-name")));
        return dataSource;
    }

}

首先根據dataSourceName通過從環境變量中獲取數據源的url,username,password和driver,然後在將剛纔的Druid基礎配置通過
@EnableConfigurationProperties(DruidConfigProperties.class)
加載進來,並set到dataSource裏,最後返回dataSource。

4.配置mybatis

@Configuration
//該註解的參數對應的類必須存在,否則不解析該註解修飾的配置類
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
public class MybatisConfiguration {


    //第一個數據源
    @Configuration
    @MapperScan(basePackages = {"com.brotherj.learn.mybatis.mapper.local"},
            sqlSessionFactoryRef = "localSqlSessionFactory")
    public static class LocalMybatisConfig{
        private final DataSource dataSource;

        public LocalMybatisConfig(@Qualifier("localDataSource") DataSource dataSource) {
            this.dataSource = dataSource;
        }

        //創建SqlSessionFactory
        @Bean
        public SqlSessionFactory localSqlSessionFactory() throws Exception {
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dataSource);
            factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                    .getResources("classpath:/mapper/local/*.xml"));
            //factoryBean.setConfigLocation(new ClassPathResource("/mapper/mybatis-config.xml"));
            return  factoryBean.getObject();
        }

        //利用SqlSessionFactory創建SqlSessionTemplate
        @Bean
        public SqlSessionTemplate localSqlSessionTemplate() throws Exception {
            return new SqlSessionTemplate(localSqlSessionFactory());
        }

        //事務
        @Bean
        public PlatformTransactionManager localTransactionManager(){
            return new DataSourceTransactionManager(dataSource);
        }
    }


    //第二個數據源
    @Configuration
    @MapperScan(basePackages = {"com.brotherj.learn.mybatis.mapper.remote"},
            sqlSessionFactoryRef = "remoteSqlSessionFactory")
    public static class RemoteMybatisConfig{
        private final DataSource dataSource;

        public RemoteMybatisConfig(@Qualifier("remoteDataSource") DataSource dataSource) {
            this.dataSource = dataSource;
        }

        //創建SqlSessionFactory
        @Bean
        public SqlSessionFactory remoteSqlSessionFactory() throws Exception {
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dataSource);
            factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                    .getResources("classpath:/mapper/remote/*.xml"));
            //factoryBean.setConfigLocation(new ClassPathResource("/mapper/mybatis-config.xml"));
            return  factoryBean.getObject();
        }

        //利用SqlSessionFactory創建SqlSessionTemplate
        @Bean
        public SqlSessionTemplate localSqlSessionTemplate() throws Exception {
            return new SqlSessionTemplate(remoteSqlSessionFactory());
        }

        //事務
        @Bean
        public PlatformTransactionManager localTransactionManager(){
            return new DataSourceTransactionManager(dataSource);
        }
    }
}

mybatis多數據源配置使用了靜態內部類的方式,之後的SqlSession和事務配置和官方提供的沒有區別。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章