版权声明:写文章不赚钱,就是交个朋友。微信公众号【Mr sirius】 https://blog.csdn.net/Sirius_hly/article/details/89139715
在传统的单体架构中,一个系统对应一个数据库,但在一个分布式系统中,比如微服务,每一个服务对应一个数据库,由于业务的需求,有时需要在一个服务中访问多个数据库的数据,需要配置多数据源,以下是SpringBoot 2.0.5 + MyBatis + .yml 格式配置多数据源的方法。
数据源配置
application.yml 文件的配置
spring:
datasource:
article-service:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: roo
jdbc-url: jdbc:mysql://localhost:3306/articleservice?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true
video-service:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: roo
jdbc-url: jdbc:mysql://localhost:3306/videoservice?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true
# 端口设置
server:
port: 8083
在单数据源的配置中,数据库地址的写法是
url: jdbc:mysql://localhost:3306
多数据源中,需要在 url 前面加上 jdbc-
jdbc-url: jdbc:mysql://localhost:3306
数据源的配置
创建多个配置类,每一个类对应一个数据源的配置,以下是一个数据源的配置。
@Configuration
//配置mbatis接口
@MapperScan(basePackages = "com.hly.springbootmybatismultidatasources.dao.ArticleService", sqlSessionFactoryRef = "articleServiceSqlSessionFactory")
public class ArticleServiceDataSourceConfig {
//将对象放入容器中
@Bean(name = "articleServiceDataSource")
//表示默认数据源
@Primary
//yml配置的对象
@ConfigurationProperties(prefix = "spring.datasource.article-service")
public DataSource getArticleServiceDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "articleServiceSqlSessionFactory")
@Primary
//@Qualifier 查找Spring 容器中名为articleServiceDataSource的对象
public SqlSessionFactory articleServiceSqlSessionFactory(@Qualifier("articleServiceDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//配置Mybatis XML文件的位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/articleService/*.xml"));
return bean.getObject();
}
@Bean(name = "articleServiceSqlSessionTemplate")
@Primary
public SqlSessionTemplate articleServiceSqlSessionTemplate(@Qualifier("articleServiceSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
Mapper & Dao
每一个数据源对应的 Mapper 和 Dao 以不同的目录区分
测试
数据库
DROP TABLE IF EXISTS `video`;
CREATE TABLE `video`(
`v_id` int(11) NOT NULL AUTO_INCREMENT,
`v_name` varchar(20) NOT NULL DEFAULT '',
`a_id` int(11) NOT NULL,
PRIMARY KEY (`v_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 DEFAULT CHARSET=utf8
DROP TABLE IF EXISTS `article`;
CREATE TABLE `article`(
`a_id` int(11) NOT NULL AUTO_INCREMENT,
`a_name` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`a_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 DEFAULT CHARSET=utf8
Mapper.xml 文件
<?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.hly.springbootmybatismultidatasources.dao.ArticleService.ArticleDao">
<resultMap id="articleResult" type="com.hly.springbootmybatismultidatasources.entity.Article">
<id column="a_id" property="a_id"/>
<result column="a_name" property="a_name"/>
</resultMap>
<select id="getArticles" resultMap="articleResult">
SELECT * FROM article;
</select>
</mapper>
<?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.hly.springbootmybatismultidatasources.dao.VideoService.VideoDao">
<resultMap id="videoResultMap" type="com.hly.springbootmybatismultidatasources.entity.Video">
<id column="v_id" property="v_id"/>
<result column="v_name" property="v_name"/>
<result column="a_name" property="a_name"/>
</resultMap>
<select id="getVideoByArticleId" parameterType="integer" resultMap="videoResultMap">
SELECT * FROM video
<if test="a_id!=null">
WHERE a_id = #{a_id}
</if>
</select>
</mapper>
Dao 接口
@Repository
public interface ArticleDao {
List<Article> getArticles();
}
@Repository
public interface VideoDao {
List<Video> getVideoByArticleId(@Param(value="a_id")int a_id);
}
Controller
@RestController
public class TestController {
@Autowired
ArticleDao articleDao;
@Autowired
VideoDao videoDao;
@RequestMapping(value = "/articles")
public Object getArticle(){
return articleDao.getArticles();
}
@RequestMapping(value = "/videos")
public Object getVideoByArticleId(int a_id){
return videoDao.getVideoByArticleId(a_id);
}
}
我的 Github:Github
个人网站: 天狼星的博客
源码下载:SpringBoot + MyBatis 配置多数据源