念念不忘
必有回响

Spring Boot整合MyBatis实现多数据源配置

Spring Boot最大的特点是简化开发,因此使用Java Config实现去xml配置,本文将使用这种方式完成对SpringBoot+Mybatis的多数据源配置。同时,会用到阿里巴巴的开源数据源Druid。

依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.liyang</groupId>
    <artifactId>op-monitor</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <!-- junit版本 -->
        <junit.version>4.11</junit.version>

        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <assertj.version>3.5.2</assertj.version>
        <!--  依赖版本  -->
        <mybatis.version>3.4.0</mybatis.version>
        <mybatis.spring.version>1.3.0</mybatis.spring.version>
        <mapper.version>3.3.6</mapper.version>
        <pagehelper.version>4.1.1</pagehelper.version>
        <!-- 阿里数据源版本 -->
        <druid.version>1.0.20</druid.version>
        <!-- Ehcache版本 -->
        <ehcache.version>3.0.0</ehcache.version>
    </properties>

    <dependencies>
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-web</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency> <!-- for ChainedTransactionManager configuration -->
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>
        <!-- 支持 @ConfigurationProperties 注解 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency> <!-- exclude掉缺省的jdbc配置 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>
        <dependency>    <!-- 加上这个才能辨认到log4j2.yml文件 -->
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>
        <!-- Mybatis Generator -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <!--分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
        <!--通用Mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>${mapper.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>0.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!-- FreeMarker 支持 -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>op-monitor</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <!-- 修改代码后自动生效,Reload Java classes without restarting the container -->
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.5.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

数据源配置

多数据源配置要求必须有一个是『主』,『主』数据源配置如下:

@Configuration
@MapperScan(basePackages = DCDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "dcSqlSessionFactory")
public class DCDataSourceConfig {
    static final String PACKAGE = "io.liyang.opmonitor.mapper.datacenter"; //数据平台DB
    @Value("${datasource.url}")
    private String dbURL;
    @Value("${datasource.username}")
    private String dbUser;
    @Value("${datasource.password}")
    private String dbPWD;

    @Bean(name = "dcDataSource")
    @Primary
    public DataSource dcDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(dbURL);
        dataSource.setUsername(dbUser);
        dataSource.setPassword(dbPWD);
        return dataSource;
    }

    @Bean(name = "dcTransactionManager")
    @Primary
    public DataSourceTransactionManager dcTransactionManager() {
        return new DataSourceTransactionManager(dcDataSource());
    }

    @Bean(name = "dcSqlSessionFactory")
    @Primary
    public SqlSessionFactory dcSqlSessionFactory(@Qualifier("dcDataSource") DataSource dcDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dcDataSource);
        return sessionFactory.getObject();
    }
}

其他数据源配置,此处只配置有一个,多个配置的话照此配置即可。

@Configuration
@MapperScan(basePackages = RedPacketDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "redPacketSqlSessionFactory")
public class RedPacketDataSourceConfig {
    static final String PACKAGE = "io.liyang.opmonitor.mapper.redpacket"; //红包平台DB
    @Value("${datasource_red.url}")
    private String dbURL;
    @Value("${datasource_red.username}")
    private String dbUser;
    @Value("${datasource_red.password}")
    private String dbPWD;

    @Bean(name = "redPacketDataSource")
    public DataSource redPacketDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(dbURL);
        dataSource.setUsername(dbUser);
        dataSource.setPassword(dbPWD);
        return dataSource;
    }

    @Bean(name = "redPacketTransactionManager")
    public DataSourceTransactionManager redPacketTransactionManager(@Qualifier("redPacketDataSource") DataSource redPacketDataSource) {
        return new DataSourceTransactionManager(redPacketDataSource);
    }

    @Bean(name = "redPacketSqlSessionFactory")
    public SqlSessionFactory redPacketSqlSessionFactory(@Qualifier("redPacketDataSource") DataSource redPacketDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(redPacketDataSource);
        return sessionFactory.getObject();
    }

}

这两个的主要区别就是扫描的包不同,这里推荐把不同数据源的Mapper放在不同的包里。

Mapper:

Mapper是mybatis的DAL层接口,其实现是由mybatis内部完成的,也就是说,我们只需要定义好接口即可完成CRUD。

@Mapper
public interface UserMapper extends MyMapper {
    @Select("select count(*) from t_user where USER_NAME=#{username} and PASSWORD=#{password}")
    int login(@Param("username") String username, @Param("password") String password);
}

SpringBootApplication配置

@SpringBootApplication
@PropertySource("classpath:db.properties")
public class BaseApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(BaseApplication.class, args);
    }

    @Override
    public SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BaseApplication.class);
    }
}

db.properties

############################
######        主DB             ######
############################
datasource.url=jdbc:mysql://10.10.10.67:3306/dc?useUnicode=true&characterEncoding=utf8&autoReconnect=true
datasource.username=adminuser
datasource.password=adminpwd
##############################
######        其它DB            ######
#############################
datasource_red.url=jdbc:mysql://10.10.10.112:6001/rcs_redbag_test?useUnicode=true&characterEncoding=utf8&autoReconnect=true
datasource_red.username=testuser
datasource_red.password=testpwd

以上配置做好以后,就可以在datacenter和redpacket两个包里分别创建两个数据源的Mapper。

赞(0) 打赏
未经允许不得转载:码农志 » Spring Boot整合MyBatis实现多数据源配置
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏