springboot项目配置两个数据源
文章目录创建一个springboot项目,并在pom中引入相关的依赖创建yml配置文件创建主启动类创建datasource配置类配置mapper与xml测试文章采用springboot+mysql+mybatis来配置两个数据库。其中数据库连接池采用的是springboot默认的 hikari ,如果想用其他的数据库连接池,请引入相关的依赖。创建一个springboot项目,并在pom中引入相关的
文章采用springboot+mysql+mybatis来配置两个数据库。其中数据库连接池采用的是springboot默认的 hikari ,如果想用其他的数据库连接池,请引入相关的依赖。
创建一个springboot项目,并在pom中引入相关的依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
//MySQL驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
//Mybatis依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
创建yml配置文件
因为我们需要配置两个数据源,而springboot默认配置DataSource时只能配置一个数据源,所以我们不能spring.dataSource
这样进行配置了,我们要自定义一个配置,如下:
# 配置主库的相关连接信息
master:
dataSource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
username: root
password: 12345678
# 配置从库的相关配置
second:
dataSource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://68.134.176.112:3306/zj?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
username: root
password: 12345678
上面的注释就表示在主库中查找springcould库中的相关信息,在从库中查找zj库中的相关信息,我这里将数据库装在了两台不同的机器上,其实也可以设置相同的ip地址,查询不同的库
创建主启动类
@SpringBootApplication
public class DatesourcetestApplication {
public static void main(String[] args) {
SpringApplication.run(DatesourcetestApplication.class, args);
}
}
创建datasource配置类
配置两个不同的数据源
首先创建一个主用于配置master数据库的配置类。
@Configuration
@MapperScan(basePackages = "com.zj.datesourcetest.master",sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
private static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";
@Value("${master.dataSource.url}")
private String url;
@Value("${master.dataSource.username}")
private String username;
@Value("${master.dataSource.password}")
private String password;
@Value("${master.dataSource.driver-class-name}")
private String driverClassName;
@Primary
@Bean("masterDataSource")
public DataSource getMasterDataSource(){
//创建一个数据源对象,springboot默认为Hikari数据源,我们也用该数据源
HikariDataSource dataSource = new HikariDataSource();
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setJdbcUrl(url);
return dataSource;
}
@Bean("masterTransactionManager")
@Primary
public TransactionManager getMasterTransactionManager(){
return new DataSourceTransactionManager
( getMasterDataSource());
}
@Bean("masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(masterDataSource);
sqlSessionFactory.setMapperLocations(
new PathMatchingResourcePatternResolver()
.getResources(MAPPER_LOCATION)
);
return sqlSessionFactory.getObject();
}
}
之后再配置second数据库的配置类
@Configuration
@MapperScan(basePackages = "com.zj.datesourcetest.second",sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {
private static final String MAPPER_LOCATION = "classpath:mapper/second/*.xml";
@Value("${second.dataSource.url}")
private String url;
@Value("${second.dataSource.username}")
private String username;
@Value("${second.dataSource.password}")
private String password;
@Value("${second.dataSource.driver-class-name}")
private String driverClassName;
@Bean("secondDataSource")
public DataSource getSecondDataSource(){
//创建一个数据源对象,springboot默认为Hikari数据源,我们也用该数据源
HikariDataSource dataSource = new HikariDataSource();
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setJdbcUrl(url);
return dataSource;
}
@Bean("secondTransactionManager")
public TransactionManager getSecondTransactionManager(){
return new DataSourceTransactionManager
( getSecondDataSource());
}
@Bean("secondSqlSessionFactory")
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource secondDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(secondDataSource);
sqlSessionFactory.setMapperLocations(
new PathMatchingResourcePatternResolver()
.getResources(MAPPER_LOCATION)
);
return sqlSessionFactory.getObject();
}
}
我们配置好了两个数据源的相关信息,就可以写mapper和xml了
配置mapper与xml
两个mapper:
@Mapper
public interface MasterMapper {
String getSerialById(int id);
}
@Mapper
public interface SecondMapper {
String getNameById(@Param("id") int id);
}
两个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.zj.datesourcetest.master.MasterMapper">
<select id="getSerialById" parameterType="int" resultType="String">
select serial from payment where id=#{id}
</select>
<!-- <insert id="savePayment" parameterType="com.zj.apiCommons.entity.Payment" useGeneratedKeys="true" keyProperty="id">-->
<!-- insert into payment(serial) values(#{serial})-->
<!-- </insert>-->
</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.zj.datesourcetest.second.SecondMapper">
<select id="getNameById" parameterType="int" resultType="String">
select newname from jjj where id=#{id}
</select>
<!-- <insert id="savePayment" parameterType="com.zj.apiCommons.entity.Payment" useGeneratedKeys="true" keyProperty="id">-->
<!-- insert into payment(serial) values(#{serial})-->
<!-- </insert>-->
</mapper>
基本的配置就已经完成了,不过先看看我的目录结构,以便于在创建项目的时候能有一个大概的了解。
测试
之后我们进行测试
测试的目的:
看看在同一个项目下是否可以对同一个项目处理两个数据库。
请自行在Test测试下测试下面两个方法
@SpringBootTest
class DatesourcetestApplicationTests {
@Autowired
private DataSource dataSource;
@Autowired
private MasterMapper masterMapper;
@Autowired
private SecondMapper secondMapper;
//主库测试
@Test
public void MasterTest(){
String serialById = masterMapper.getSerialById(1);
System.out.println(serialById);
}
//从库配置
@Test
public void SecondTest(){
String nameById = secondMapper.getNameById(23);
System.out.println(nameById);
}
}
测试后不报错就可以,至于数据库,请自行创建一些表自行测试
如果想要参考源代码,可以访问我的github地址进行拉取:
https://github.com/2290653824/springfamilybucket/tree/main/springfamilybucket/datesourcetest
更多推荐
所有评论(0)