從零搭建自己的SpringBoot後臺框架(十一)

Mr_初晨發表於2018-04-29
Hello大家好,本章我們配置多資料來源功能 。有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝

一:配置資料來源

修改application.properties

spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.db1.url=jdbc:mysql://localhost:3333/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false
spring.datasource.db1.username=root
spring.datasource.db1.password=123456
spring.datasource.db1.initialSize=5
spring.datasource.db1.minIdle=5
spring.datasource.db1.maxActive=20
#連線等待超時時間
spring.datasource.db1.maxWait=60000
#配置隔多久進行一次檢測(檢測可以關閉的空閒連線)
spring.datasource.db1.timeBetweenEvictionRunsMillis=60000
#配置連線在池中的最小生存時間
spring.datasource.db1.minEvictableIdleTimeMillis=300000
spring.datasource.db1.validationQuery=SELECT 1 FROM DUAL
spring.datasource.db1.testWhileIdle=true
spring.datasource.db1.testOnBorrow=false
spring.datasource.db1.testOnReturn=false
# 開啟PSCache,並且指定每個連線上PSCache的大小
spring.datasource.db1.poolPreparedStatements=true
spring.datasource.db1.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆
spring.datasource.db1.filters=stat,wall,slf4j
# 通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
spring.datasource.db1.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000


spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.db2.url=jdbc:mysql://localhost:3306/chuchen?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false
spring.datasource.db2.username=root
spring.datasource.db2.password=123456
spring.datasource.db2.initialSize=5
spring.datasource.db2.minIdle=5
spring.datasource.db2.maxActive=20
#連線等待超時時間
spring.datasource.db2.maxWait=60000
#配置隔多久進行一次檢測(檢測可以關閉的空閒連線)
spring.datasource.db2.timeBetweenEvictionRunsMillis=60000
#配置連線在池中的最小生存時間
spring.datasource.db2.minEvictableIdleTimeMillis=300000
spring.datasource.db2.validationQuery=SELECT 1 FROM DUAL
spring.datasource.db2.testWhileIdle=true
spring.datasource.db2.testOnBorrow=false
spring.datasource.db2.testOnReturn=false
# 開啟PSCache,並且指定每個連線上PSCache的大小
spring.datasource.db2.poolPreparedStatements=true
spring.datasource.db2.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆
spring.datasource.db2.filters=stat,wall,slf4j
# 通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
spring.datasource.db2.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000複製程式碼

注意修改為自己的資料庫連線

二:建立資料來源配置

MysqlDataSource1Config

package com.example.demo.core.configurer.dataSource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.example.demo.dao.db1"})
public class MysqlDataSource1Config {

    @Bean(name = "primaryDataSource")
    //需設定主資料來源
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.db1")
    public DataSource dataSource(){
        //跟之前不一樣了
        return new DruidDataSource();
    }

    @Bean(name = "primaryTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(dataSource());

    }

    @Bean(name="primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("primaryDataSource")DataSource primaryDataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(primaryDataSource);
        Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db1/*.xml");
        sessionFactory.setMapperLocations(mapperLocations);
        return sessionFactory.getObject();
    }
}
複製程式碼

MysqlDataSource2Config

package com.example.demo.core.configurer.dataSource;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.example.demo.dao.db2"}, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class MysqlDataSource2Config {

    @Bean(name = "secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db2/*.xml");
        sessionFactory.setMapperLocations(mapperLocations);
        return sessionFactory.getObject();
    }
}複製程式碼

三:修改目錄結構

目錄結構如下圖,db1為主資料來源,db2為從資料來源,這樣根據訪問dao層不同,會自動進行資料來源切換

從零搭建自己的SpringBoot後臺框架(十一)

四:功能測試

輸入http://localhost:8080/userInfo/selectAll

結果:

{
    "code": 200,
    "data": {
        ....省略
        "list": [
            {
                "id": "1",
                "userName": "Mr_初晨"
            },
            {
                "id": "2",
                "userName": "Mr_初晨"
            }
        ],
        .....省略
    },
    "msg": "success"
}複製程式碼

輸入http://localhost:8080/userLabel/list

結果:

{
    "code": 200,
    "data": {
        ....省略
        "list": [
             {
                "createTime": 1523283547000,
                "id": "24084baed3c6409a8619a635bf4428a1",
                "labelId": "4",
                "userId": "1"
            }
        ],
        .....省略
    },
    "msg": "success"
}複製程式碼

輸入http://localhost:8080/druid/datasource.html

也可以看見有兩個資料來源

專案地址

碼雲地址: gitee.com/beany/mySpr…

GitHub地址: github.com/MyBeany/myS…

寫文章不易,如對您有幫助,請幫忙點下star從零搭建自己的SpringBoot後臺框架(十一)

結尾

配置多資料來源功能已完成,後續功能接下來陸續更新,有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝大家。



相關文章