springboot整合多数据源
一、前言
springboot整合多数据源 (采用分包策略)。
在此记录下,分享给大家。
二、springboot整合多数据源
1、pom文件 依赖引入
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<!-- SpringBoot 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis 支持 SpringBoot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- SpringBoot web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2、 application.yml 新增配置
spring:
datasource:
## 用户数据库
user:
jdbc-url: jdbc:mysql://127.0.0.1:3306/yys_user
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
## 订单数据库
order:
jdbc-url: jdbc:mysql://127.0.0.1:3306/yys_order
username: root
password: 123456.
driver-class-name: com.mysql.jdbc.Driver
3、userDataSourceConfig.java - com.yys.config.user
/**
* 用户数据源
* Config
* @author yys
*/
@Configuration
@MapperScan(basePackages = "com.yys.user", sqlSessionTemplateRef = "userSqlSessionTemplate")
public class UserDataSourceConfig {
/**
* 创建 DataSource
* @return
*/
@Bean("userDataSource")
@ConfigurationProperties("spring.datasource.user")
public DataSource userDataSource() {
return DataSourceBuilder.create().build();
}
/**
* 创建 SQL会话工厂
* @param dataSource
* @return
* @throws Exception
*/
@Bean("userSqlSessionFactory")
public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean.getObject();
}
/**
* 创建 事务管理器
* @param dataSource
* @return
*/
@Bean("userTransactionManager")
public DataSourceTransactionManager userTransactionManager(@Qualifier("userDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
/**
* 创建用户 SqlSession模板
* @param sqlSessionFactory
* @return
*/
@Bean("userSqlSessionTemplate")
public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
4、orderDataSourceConfig.java - com.yys.config.order
/**
* 订单数据源
* Config
* @author yys
*/
@Configuration
@MapperScan(basePackages = "com.yys.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")
public class OrderDataSourceConfig {
/**
* 创建 DataSource
* @return
*/
@Bean("orderDataSource")
@ConfigurationProperties("spring.datasource.order")
public DataSource orderDataSource() {
return DataSourceBuilder.create().build();
}
/**
* 创建 SQL会话工厂
* @param dataSource
* @return
* @throws Exception
*/
@Bean("orderSqlSessionFactory")
public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean.getObject();
}
/**
* 创建 事务管理器
* @param dataSource
* @return
*/
@Bean("orderTransactionManager")
public DataSourceTransactionManager orderTransactionManager(@Qualifier("orderDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
/**
* 创建订单 SqlSession模板
* @param sqlSessionFactory
* @return
*/
@Bean("orderSqlSessionTemplate")
public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
5、MybatisController.java
/**
* 多数据源测试
* Controller
* @author yys
*/
@RestController
@RequestMapping("/add")
public class MybatisController {
@Autowired
private UserMapper userMapper;
@Autowired
private OrderMapper orderMapper;
/**
* 新增用户
* @return
*/
@RequestMapping("/user")
public String addUser(String name, Integer age) {
return userMapper.addUser(name, age) > 0 ? "addUser success" : "addUser fail";
}
/**
* 新增订单
* @return
*/
@RequestMapping("/order")
public String addOrder(Double amount, String address) {
return orderMapper.addOrder(amount, address) > 0 ? "addOrder success" : "addOrder fail";
}
}
6、UserMapper.java
/**
* 用户管理
* Mapper
* @author yys
*/
public interface UserMapper {
@Insert("INSERT INTO user VALUES (NULL, #{name}, #{age}, 1, NOW(), NOW())")
int addUser(@Param("name") String name, @Param("age") Integer age);
}
7、OrderMapper.java
/**
* 订单管理
* Mapper
* @author yys
*/
public interface OrderMapper {
// order为数据库关键字,记得使用``
@Insert("INSERT INTO `order` VALUES (NULL, #{amount}, #{address}, 1, NOW(), NOW())")
int addOrder(@Param("amount") Double amount, @Param("address") String address);
}
8、启动类
@SpringBootApplication
@MapperScan("com.yys.mapper")
public class YysApp {
public static void main(String[] args) {
SpringApplication.run(YysApp.class, args);
}
}
9、初始化sql文件
-- Database:yys_user
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'ID,自增列',
`name` varchar(32) NOT NULL COMMENT '用户名',
`age` int(11) NOT NULL COMMENT '用户年龄',
`status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态:-1-删除;1-正常;',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
-- Database:yys_order
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'ID,自增列',
`amount` double(11,2) NOT NULL COMMENT '订单金额',
`address` varchar(32) NOT NULL COMMENT '地址',
`status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态:-1-删除;1-正常;',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
10、测试
http://localhost:8080/add/user?name=洞人&age=18
a、页面结果 - 如下图所示 :
b、数据库结果 - 如下图所示 :
http://localhost:8080/add/order?amount=10.24&address=山顶
a、页面结果 - 如下图所示 :
b、数据库结果 - 如下图所示 :
Now ~ ~ ~写到这里,就写完了,如果有幸帮助到你,请记得关注我,共同一起见证我们的成长。