Spring Boot + MyBatis + MySQL 实现读写分离!
在Spring Boot项目中实现读写分离,可以通过以下步骤:
- 引入依赖(在pom.xml中):
<!-- 数据源 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.5</version>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
- 配置application.properties或application.yml文件:
# 主数据源配置
spring.datasource.primary.jdbc-url=jdbc:mysql://主数据库地址:3306/数据库名?useSSL=false&serverTimezone=UTC
spring.datasource.primary.username=用户名
spring.datasource.primary.password=密码
# 从数据源配置
spring.datasource.secondary.jdbc-url=jdbc:mysql://从数据库地址:3306/数据库名?useSSL=false&serverTimezone=UTC
spring.datasource.secondary.username=用户名
spring.datasource.secondary.password=密码
- 配置数据源和MyBatis:
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource primaryDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(primaryDataSource);
return sqlSessionFactoryBean.getObject();
}
}
- 使用注解指定操作的数据源:
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
评论已关闭