springboot+druid+mybatis配置多数据源

这几天和朋友准备用springboot做一个简单的资金管理系统,搭框架的过程中,想配置一个多数据源,用于实现数据库分库,今天测试成功,特将过程记录下来。一共两种方法,记录在此。

1.代码如下
配置文件

server.port=8888
server.servlet.context-path=/honeybee

#druid
spring.datasource.druid.master.name=master
spring.datasource.druid.master.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.master.url=jdbc:mysql://localhost:3306/honeybee?useUnicode=true&characterEncoding=utf8
spring.datasource.druid.master.username=root
spring.datasource.druid.master.password=password

#spring.datasource.druid.slave.name=master
#spring.datasource.druid.slave.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.druid.slave.url=jdbc:mysql://localhost:3306/honeybee?useUnicode=true&characterEncoding=utf8
#spring.datasource.druid.slave.username=root
#spring.datasource.druid.slave.password=password

# Druid dataSource config
spring.datasource.druid.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initialSize=10
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.poolPreparedStatements=false
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=select 'x'
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.maxOpenPreparedStatements=-1

# Druid stat filter config
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/druid/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.css,/druid*,*.jsp,*.swf
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.session-stat-max-count=10
#spring.datasource.druid.web-stat-filter.principal-session-name=
#spring.datasource.druid.web-stat-filter.principal-cookie-name=
spring.datasource.druid.web-stat-filter.profile-enable=true
spring.datasource.druid.filter.stat.db-type=mysql
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=1000
spring.datasource.druid.filter.stat.merge-sql=true
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=mysql
spring.datasource.druid.filter.wall.config.delete-allow=true
spring.datasource.druid.filter.wall.config.drop-table-allow=false

# Druid manage page config
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin

# Druid AOP config
#Spring监控AOP切入点
spring.datasource.druid.aop-patterns=com.honeybee.service.*
spring.aop.proxy-target-class=true

#mybatis config
mybatis.type-aliases-package=com.honeybee.common.bean
mybatis.mapper-locations=classpath:mapper/*.xml

DataSource.java

/**
 * 定义获取SqlSessionFactory对象的父类,用于被继承
 * @author HXY
 * @version 1.0
 */
public class DataSource {
    /**
     * 配置 SqlSessionFactoryBean
     * @return
     * @throws Exception
     */
    public SqlSessionFactory sqlSessionFactory(javax.sql.DataSource dataSource, String mapperLocation, String typePackage)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(mapperLocation));
        sessionFactory.setTypeAliasesPackage(typePackage);

        return sessionFactory.getObject();
    }
}

第一个数据源实现类:MasterDtaSource.java

/**
 * 配置多数据源
 * @author HXY
 * @version 1.0
 */
@Configuration
@MapperScan(basePackages = MasterDataBase.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataBase extends DataSource {
    static final String PACKAGE = "com.honeybee.dao";

    @Value("${mybatis.type-aliases-package}")
    private String typePackage;

    @Value("${mybatis.mapper-locations}")
    private String mapperLocation;

    /**
     * 配置数据源
     * @return
     */
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
    @Bean(name="masterDataSource")
    public javax.sql.DataSource dataSource()throws Exception{
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 配置事务管理,如果使用到事务需要注入该 Bean,否则事务不会生效
     * 在需要的地方加上 @Transactional 注解即可
     * @return
     */
    @Bean(name = "masterTransactionManager")
    public DataSourceTransactionManager masterTransactionManager() throws Exception{
        return new DataSourceTransactionManager(dataSource());
    }

    /**
     * 配置 SqlSessionFactoryBean
     * @return
     * @throws Exception
     */
    @Bean(name = "masterSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") javax.sql.DataSource masterDataSource)
            throws Exception {
        return sqlSessionFactory(masterDataSource, mapperLocation, typePackage);
    }
}

第二个数据源实现类:SlaveDtaSource.java

/**
 * 配置多数据源
 * @author HXY
 * @version 1.0
 */
@Configuration
@MapperScan(basePackages = SlaveDataBase.PACKAGE, sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class SlaveDataBase extends DataSource{
    static final String PACKAGE = "com.honeybee.dao";

    @Value("${mybatis.type-aliases-package}")
    private String typePackage;

    @Value("${mybatis.mapper-locations}")
    private String mapperLocation;

    /**
     * 配置数据源
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource.druid.slave")
    @Bean(name = "slaveDataSource")
    public javax.sql.DataSource dataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 配置事务管理,如果使用到事务需要注入该 Bean,否则事务不会生效
     * 在需要的地方加上 @Transactional 注解即可
     * @return
     */
    @Bean(name = "slaveTransactionManager")
    @Primary
    public DataSourceTransactionManager slaveTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }


    /**
     * 配置 SqlSessionFactoryBean
     * @return
     * @throws Exception
     */
    @Bean(name = "slaveSqlSessionFactory")
    @Primary
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") javax.sql.DataSource slaveDataSource)
            throws Exception {
        return sqlSessionFactory(slaveDataSource, mapperLocation, typePackage);
    }
}

2.第二种方法参考自github项目,连接如下:
动态数据源github地址

你可能感兴趣的:(Spring)