1. 程式人生 > >Spring Boot + mybatic + 多資料來源 自動切換

Spring Boot + mybatic + 多資料來源 自動切換

寫在開篇

Spring boot 最大的特點就是簡化開發(去xml配置)。故這篇所實現的也是配置些註解,並無大量的xml配置。

外甥打燈籠--照舊上程式碼

依賴其他依賴省去。    

<dependency>
	<groupId>com.zaxxer</groupId>
	<artifactId>HikariCP</artifactId>
</dependency>

資料來源配置:多資料來源配置要求必須有一個主配置,多個輔配置

/**
 * Created by echo on 2017/3/21.
 */
@Configuration
@ComponentScan(basePackageClasses = DalModule.class)
@MapperScan(basePackages = "com.livecho.dal.mapper.one", sqlSessionFactoryRef = "oneSqlSessionFactory")
public class DalModule {

    @Value("${demo-one.db-driver}")
    private String driver;

    @Value("${demo-one.db-url}")
    private String jdbcUrl;

    @Value("${demo-one.db-username}")
    private String dbUser;

    @Value("${demo-one.db-password}")
    private String dbPassword;

    @Bean(name = "oneDataSource")
    @Primary
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(driver);
        hikariConfig.setJdbcUrl(jdbcUrl);
        hikariConfig.setUsername(dbUser);
        hikariConfig.setPassword(dbPassword);
        hikariConfig.setPoolName("springHikariCP");
        hikariConfig.setAutoCommit(false);
        hikariConfig.addDataSourceProperty("cachePrepStmts", "true");
        hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250");
        hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        hikariConfig.addDataSourceProperty("useServerPrepStmts", "true");

        hikariConfig.setMinimumIdle(1);
        hikariConfig.setMaximumPoolSize(20);
        hikariConfig.setConnectionInitSql("SELECT 1");

        HikariDataSource dataSource = new HikariDataSource(hikariConfig);
        return dataSource;
    }

    @Bean
    @Primary
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean("demo-one")
    @Primary
    public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }

    @Bean(name = "oneSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("oneDataSource") DataSource oneDataSource) throws Exception {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(oneDataSource);
        sessionFactory.setFailFast(true);
        sessionFactory.setMapperLocations(resolver.getResources("classpath:/config/one/*Mapper.xml"));
        return sessionFactory.getObject();
    }

說明:

    @Configuration:自動配置。等同於spring的xml配置檔案。

    @Value:注入 springBoot的application.properties配置的屬性值

    @MapperScan:指定要掃描的Mapper類的包路徑。

    @Primary:註解的例項 優先其他例項被注入。

副配置

@Configuration
@ComponentScan(basePackageClasses = DalModuleTwo.class)
@MapperScan(basePackages = "com.livecho.dal.mapper.two", sqlSessionFactoryRef = "twoSqlSessionFactory")
public class DalModuleTwo {

    @Value("${demo-two.db-driver}")
    private String driver;

    @Value("${demo-two.db-url}")
    private String jdbcUrl;

    @Value("${demo-two.db-username}")
    private String dbUser;

    @Value("${demo-two.db-password}")
    private String dbPassword;

    @Bean(name = "twoDataSource")
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(driver);
        hikariConfig.setJdbcUrl(jdbcUrl);
        hikariConfig.setUsername(dbUser);
        hikariConfig.setPassword(dbPassword);
        hikariConfig.setPoolName("springHikariCP");
        hikariConfig.setAutoCommit(false);
        hikariConfig.addDataSourceProperty("cachePrepStmts", "true");
        hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250");
        hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        hikariConfig.addDataSourceProperty("useServerPrepStmts", "true");

        hikariConfig.setMinimumIdle(1);
        hikariConfig.setMaximumPoolSize(20);
        hikariConfig.setConnectionInitSql("SELECT 1");

        HikariDataSource dataSource = new HikariDataSource(hikariConfig);
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean("demo-two")
    public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }

    @Bean(name = "twoSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("twoDataSource") DataSource twoDataSource) throws Exception {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(twoDataSource);
        sessionFactory.setFailFast(true);
        sessionFactory.setMapperLocations(resolver.getResources("classpath:/config/two/*Mapper.xml"));
        return sessionFactory.getObject();
    }

和主配置的區別:

    1、少了@Primary這個註解

    2、sqlSessionFactory的名稱區別開

    3、mapper.xml的路徑 區別開

    4、mapperScan 掃描包地址 區別開

資料來源配置

demo-one:
  db-driver: com.mysql.jdbc.Driver
  db-url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf8
  db-username: root
  db-password: root

demo-two:
  db-driver: com.mysql.jdbc.Driver
  db-url: jdbc:mysql://127.0.0.1:3306/demoTwo?useUnicode=true&characterEncoding=utf8
  db-username: root
  db-password: root

專案結構圖:

總結說明:

    1、配置簡單:

        a、application.properties配置多個數據源

        b、配置多個數據庫連線池(必須有一主@Primary)

        c、注意不同資料庫的表mapper、dao、xml物件存放不同路徑

    2、不影響開發流程:

        a、不用在呼叫mapper處指定資料來源。

        b、業務開發流程不變。controller->service->serviceImpl->repository->repositoryImpl->mapper->xml