SpringBoot(三):多数据源配置

说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务,配置多数据源重点是配置文件,所以数据库,pox文件,实体类我都不发出来了,自己创建两个数据库,配置实体类就行了

版权声明:本文由 低调小熊猫 发表于 低调小熊猫的博客

转载声明:自由转载-非商用-非衍生-保持署名,非商业转载请注明作者及出处,商业转载请联系作者本人qq:2696284032

文章链接: https://aodeng.cc/archives/springboot-san


排除自动配置

springboot会自动读取配置文件,由于我们需要配置多数据源,所以要排除自动配置,在启动入口添加如下注解

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})


配置数据源

在application.yml中配置两个数据源

spring:
  datasource:
    first:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: XXX
      password: XXX
      type: com.alibaba.druid.pool.DruidDataSource
      initial-size: 1
      minIdle: 3
      maxActive: 20
      maxWait: 60000
      filters: stat,wall,slf4j
    second:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: XXX
      password: XXX
      type: com.alibaba.druid.pool.DruidDataSource


创建配置文件封装类

@ConfigurationProperties
注解指定数据来源

1.FirstDataProperties类

package com.ad.core.hope.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-08-31 13:46
 **/
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.first")
public class FirstDataProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}

2.SecondDataProperties类

package com.ad.core.hope.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-08-31 13:47
 **/
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.second")
public class SecondDataProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}


数据源配置

这里面的代码才是最重要的

注: @Primary
必须使用该注解指定主数据源

@MapperScan
指定路径下的mapper使用该数据源

1.FirstDataSourceConfig配置

package com.ad.core.hope.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-08-02 20:16
 **/

@Configuration
@MapperScan(basePackages = "com.ad.core.hope.mapper.first",sqlSessionTemplateRef = "firstSqlSessionTemplate")
public class FirstDataSourceConfig {

    @Autowired
    private FirstDataProperties firstprop;

    //创建数据源
    @Bean(name="firstDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.first")

    public DataSource getFirstDataSource(){
        DataSource build = DataSourceBuilder.create()
                .driverClassName(firstprop.driverClassName)
                .url(firstprop.url)
                .username(firstprop.username)
                .password(firstprop.password).build();
     return build;
    }

    //创建SqlSessionFactory
    @Bean(name = "firstSqlSessionFactory")

    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception{
     SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
     bean.setDataSource(dataSource);
     return bean.getObject();
    }

    //创建事务管理器
    @Bean(name = "firstTransactionManager")

    public DataSourceTransactionManager firstTransactionManager(@Qualifier("firstDataSource") DataSource dataSource){
     return new DataSourceTransactionManager(dataSource);
    }

    //创建SqlSessionTemplate
    @Bean(name = "firstSqlSessionTemplate")

    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws  Exception{
     return new SqlSessionTemplate(sqlSessionFactory);
    }

    private Class getType(String type){
        try {
            return Class.forName(type);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        return null;
    }
}

2.SecondDataSourceConfig配置

package com.ad.core.hope.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-08-02 20:16
 **/

@Configuration
@MapperScan(basePackages = "com.ad.core.hope.mapper.second",sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class SecondDataSourceConfig {

    @Autowired
    private SecondDataProperties secondprop;

    //创建数据源
    @Bean(name="secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    @Primary
    public DataSource getSecondDataSource(){
        DataSource build = DataSourceBuilder.create()
                .driverClassName(secondprop.driverClassName)
                .url(secondprop.url)
                .username(secondprop.username)
                .password(secondprop.password).build();
        return build;
    }

    //创建SqlSessionFactory
    @Bean(name = "secondSqlSessionFactory")
    @Primary
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    //创建事务管理器
    @Bean(name = "secondTransactionManager")
    @Primary
    public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    //创建SqlSessionTemplate
    @Bean(name = "secondSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws  Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    private Class getType(String type){
        try {
            return Class.forName(type);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        return null;
    }
}


实现Mapper

注:该mapper的路径必须和 @MapperScan
注解的指定路径一样

1.first路径下的mapepr

package com.ad.core.hope.mapper.first;

import com.ad.core.hope.enums.TestUserEnum;
import com.ad.core.hope.vo.base.TestVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface TestInterface {

    @Select("SELECT * FROM user")
    @Results({
            @Result(property = "sex", column = "sex", javaType = TestUserEnum.class),
            @Result(property = "name", column = "username")
    })
    List<TestVo> getAll();
}

2.second路径下的mapper

package com.ad.core.hope.mapper.second;

import com.ad.core.hope.model.admin.SysUser;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-09-02 17:25
 **/
@org.apache.ibatis.annotations.Mapper
public interface TestMapper{
    @Select("SELECT * FROM sys_user")
    @Results({
            @Result(property = "userid", column = "userId"),
            @Result(property = "username", column = "username")
    })
    List<SysUser> getAll();
}


Controller使用

使用 @Autowired
注解装配mapper使用

@Controller
public class TeseController {

    @Autowired
    private TestInterface testInterface;

    @Autowired
    private TestMapper testMapper;

    @RequestMapping("/login")
    public String login(Model model){
        //数据源first测试
        List<TestVo> list=testInterface.getAll();
        for(int i=0;i<list.size();i++){
            System.out.println("测试fisrt数据源"+list.get(i).getName());
        }
        //数据源second测试
        List<SysUser> user=testMapper.getAll();
        for(int i=0;i<user.size();i++){
            System.out.println("测试second数据源"+user.get(i).getUsername());
        }
        return "admin/system_login";
    }
}

原文 

https://aodeng.cc/archives/springboot-san

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » SpringBoot(三):多数据源配置

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址