码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot2.0之八 多数据源配置

时间:2019-04-29 19:03:51      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:sdn   adduser   masters   parameter   detail   classname   .com   system   primary   

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

一、建立如下结构的maven项目

技术图片
二、添加相关数据库配置信息

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());
}
}

当在控制台看到如下所示输出就代表我们的配置已经成功了

技术图片
Git代码地址:https://gitee.com/Somta/SpringBoot/tree/master/SpringBoot-multiDatasource
原文地址:http://somta.com.cn/#/blog/view/05ef234aa6744aa4bc039869e2cfaffe
---------------------
作者:明天的地平线
来源:CSDN
原文:https://blog.csdn.net/husong_/article/details/80103497
版权声明:本文为博主原创文章,转载请附上博文链接!

SpringBoot2.0之八 多数据源配置

标签:sdn   adduser   masters   parameter   detail   classname   .com   system   primary   

原文地址:https://www.cnblogs.com/telwanggs/p/10791976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!