记录一下springboot
配置多数据源的过程
本文完整代码git
地址:https://github.com/liaozq0426/springboot-many-datasource.git
- 引入jar包,其中
druid-spring-boot-starter
为阿里巴巴数据库连接池框架druid
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
- 在
spring
配置文件application.yml
中定义数据库连接信息,项目中使用了两个数据源,分别为master
和slave
,对应本地的两个数据库
spring:
profiles:
active: dev
---
#开发环境
spring:
profiles: dev
#数据源
datasource:
#阿里druid数据库连接池
druid:
filters: mergeStat,wall
initial-size: 5
max-active: 50
min-idle: 5
max-wait: 6000
validation-query: SELECT 'x'
test-on-borrow: true
test-on-return: true
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
remove-abandoned: true
remove-abandoned-timeout: 1800
log-abandoned: true
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: false
login-username: admin
login-password: 123456
#主数据源
master:
url: jdbc:mysql://localhost:3306/master?characterEncoding=utf8&serverTimezone=CTT
username: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
#从数据源
slave:
url: jdbc:mysql://localhost:3306/slave?characterEncoding=utf8&serverTimezone=CTT
username: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
- 配置主从数据源,主数据源类为
MasterDruidConfiguration
import java.sql.SQLException;
import javax.sql.DataSource;
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.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
@Configuration
//扫描mapper接口
@MapperScan(basePackages = {"com.gavin.mapper.master"}, sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterDruidConfiguration {
// 读取数据源配置信息
@ConfigurationProperties(prefix = "spring.datasource.druid.master")
@Bean(name = "masterDataSource")
@Primary
public DataSource dataSource() throws SQLException{
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 加载mybatis配置文件
Resource resourcesMybatis = resolver.getResource("classpath:/mybatis/mybatis-config.xml");
// 加载mapper文件
Resource[] resourcesMapper = resolver.getResources("classpath*:/mybatis/master/*.xml");
bean.setMapperLocations(resourcesMapper);//对应mapper.xml的具体位置
bean.setConfigLocation(resourcesMybatis);
return bean.getObject();
}
@Bean(name = "masterTransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "masterSqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
从数据源配置类为SlaveDruidConfiguration
import java.sql.SQLException;
import javax.sql.DataSource;
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.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
@Configuration
// 扫描mapper接口
@MapperScan(basePackages = {"com.gavin.mapper.slave"}, sqlSessionTemplateRef = "slaveSqlSessionTemplate")
public class SlaveDruidConfiguration {
// 读取数据源配置信息
@ConfigurationProperties(prefix = "spring.datasource.druid.slave")
@Bean(name = "slaveDataSource")
public DataSource dataSource() throws SQLException{
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "slaveSqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 加载mybatis配置文件
Resource resourcesMybatis = resolver.getResource("classpath:/mybatis/mybatis-config.xml");
// 加载mapper文件
Resource[] resourcesMapper = resolver.getResources("classpath:/mybatis/slave/*.xml");
bean.setMapperLocations(resourcesMapper);
bean.setConfigLocation(resourcesMybatis);
return bean.getObject();
}
@Bean(name = "slaveTransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "slaveSqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
如果项目中没用定义mybatis-config.xml
配置文件,可在代码中注释掉相应的加载代码
// 加载mybatis配置文件
Resource resourcesMybatis = resolver.getResource("classpath:/mybatis/mybatis-config.xml");
bean.setConfigLocation(resourcesMybatis);
多数据源配置到此结束,接下来我们编写简单的代码使用一下,分别向 master
数据库的user
表和slave
数据库的person
表中插入一条数据
- 创建实体类
User
和Person
public class User {
private Integer userId; // 自增主键
private String userName;
private String password;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class Person {
private Integer personId; // 自增主键
private String personName;
private Integer age;
public Integer getPersonId() {
return personId;
}
public void setPersonId(Integer personId) {
this.personId = personId;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
- 创建
mapper
接口UserMapper
和PersonMapper
import com.gavin.entity.User;
public interface UserMapper {
int insert(User user);
}
import com.gavin.entity.Person;
public interface PersonMapper {
int insert(Person person);
}
- 创建业务接口以及实现类
DataProcessService
接口
public interface DataProcessService {
public void insertData() throws Exception;
}
DataProcessServiceImpl
接口实现类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gavin.entity.Person;
import com.gavin.entity.User;
import com.gavin.mapper.master.UserMapper;
import com.gavin.mapper.slave.PersonMapper;
import com.gavin.service.DataProcessService;
@Service
public class DataProcessServiceImpl implements DataProcessService {
@Autowired
private UserMapper userMapper;
@Autowired
private PersonMapper personMapper;
@Override
public void insertData() throws Exception {
// 创建user
User user = new User();
user.setUserName("张萌萌");
user.setPassword("123456");
// 创建person
Person person = new Person();
person.setAge(23);
person.setPersonName("李依依");
// 保存user
int userFlag = userMapper.insert(user);
int personFlag = personMapper.insert(person);
System.out.println("保存user标识:" + userFlag);
System.out.println("保存person标识:" + personFlag);
}
}
- 最后创建
DataProcessController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gavin.service.DataProcessService;
@RestController
@RequestMapping("dp")
public class DataProcessController {
@Autowired
private DataProcessService dataProcessService;
@GetMapping("add")
public String addData(){
try {
dataProcessService.insertData();
return "success";
} catch (Exception e) {
e.printStackTrace();
return "fail";
}
}
}
启动程序,访问localhost:8080/dp/add
,后台打印
查看数据库可以看到user
表和person
表分别插入成功一条记录!