欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot2.0之八 多数据源配置

程序员文章站 2024-03-17 21:00:46
...

  在开发的过程中我们可能都会遇到对接公司其他系统等需求,对于外部的系统可以采用接口对接的方式,对于一个公司开发的两个系统,并且知道相关数据库结构的情况下,就可以考虑使用多数据源来解决这个问题。SpringBoot为我们提供了相对简单的实现。

一、建立如下结构的maven项目
SpringBoot2.0之八 多数据源配置

二、添加相关数据库配置信息

server:
  port: 8080

spring:  
  datasource:
    master:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456
    slaver:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/dev?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456

三、主库和从库的相关配置
1、主库数据源配置

@Configuration
@MapperScan(basePackages = "com.somta.springboot.dao.master", sqlSessionTemplateRef  = "masterSqlSessionTemplate")
public class MasterDataSourceConfiguration {

    @Value("${spring.datasource.master.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.master.url}")
    private String url;

    @Value("${spring.datasource.master.username}")
    private String username;

    @Value("${spring.datasource.master.password}")
    private String password;

    @Bean(name = "masterDataSource")
    @Primary
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/master/**/Mysql_*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "masterSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

2、从库的数据源配置信息

@Configuration
@MapperScan(basePackages = "com.somta.springboot.dao.slaver", sqlSessionTemplateRef  = "slaverSqlSessionTemplate")
public class SlaverDataSourceConfiguration {

    @Value("${spring.datasource.slaver.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.slaver.url}")
    private String url;

    @Value("${spring.datasource.slaver.username}")
    private String username;

    @Value("${spring.datasource.slaver.password}")
    private String password;


    @Bean(name = "slaverDataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }

    @Bean(name = "slaverSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("slaverDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/slaver/**/Mysql_*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "slaverTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("slaverDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "slaverSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaverSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

  注意在配置数据源的信息时,一定要通过@Primary配置一个主库,对于数据库配置部分与普通的数据源配置没有差异,新建一个DataSource,在创建一个SqlSessionTemplate,最后创建一个SqlSessionTemplate,分别以此注入即可,@MapperScan注解的扫描路径要分别对于相应的dao层

四、编写dao层和xml

public interface UserMasterDao {
    int addUser(User user);
    int deleteUserById(Long id);
    int updateUserById(User user);
    User queryUserById(Long id);
    List<User> queryUserList();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.somta.springboot.dao.master.UserMasterDao" > 
<!-- Result Map-->
<resultMap id="BaseResultMap" type="com.somta.springboot.pojo.User" >
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="age" property="age"/>
</resultMap>

<!-- th_role_user table all fields -->
<sql id="Base_Column_List" >
    id, name, age
</sql>

<insert id="addUser" parameterType="com.somta.springboot.pojo.User" >
    insert into t_user (id, name, age) 
    values (#{id},#{name},#{age});
</insert>

<delete id="deleteUserById" parameterType="java.lang.Long">
 delete from t_user where id=#{id}
</delete>

<update id="updateUserById" parameterType="com.somta.springboot.pojo.User" >
    update t_user set 
    <trim  suffixOverrides="," >
    <if test="id != null and id != ''">
        id=#{id},
    </if>
    <if test="name != null and name != ''">
        name=#{name},
    </if>
    <if test="age != null and age != ''">
        age=#{age},
    </if>
    </trim> where id=#{id}
</update>

<select id="queryUserById" resultMap="BaseResultMap" parameterType="java.lang.Long">
    select <include refid="Base_Column_List" /> 
    from t_user where id = #{id}
</select>

<select id="queryUserList" resultMap="BaseResultMap">
    select <include refid="Base_Column_List" /> 
    from t_user
</select>

</mapper>   

五、编写测试类进行测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class MultiDatasourceTest {
    @Autowired
    private UserMasterDao masterUserDao;
    @Autowired
    private UserSlaverDao slaverUserDao;
    /**
     * 查询用户
     * @throws Exception
     */
    @Test
    public void testQueryUser() throws Exception {
        User masterUser = masterUserDao.queryUserById(1L);
        System.out.println("masterUser==>"+masterUser.getName());

        User slaverUser = slaverUserDao.queryUserById(1L);
        System.out.println("slaverUser==>"+slaverUser.getName());
    }
}

当在控制台看到如下所示输出就代表我们的配置已经成功了
SpringBoot2.0之八 多数据源配置

Git代码地址:https://gitee.com/Somta/SpringBoot/tree/master/SpringBoot-multiDatasource
原文地址:http://somta.com.cn/#/blog/view/05ef234aa6744aa4bc039869e2cfaffe

  本文由明天的地平线创作,如想了解更多更详细的内容,请关注一下公众号,公众号内将进行最新最实时的更新!
SpringBoot2.0之八 多数据源配置