温馨提示×

如何使用Spring Boot实现MySQL的读写分离

小樊
84
2024-08-07 00:14:21
栏目: 云计算

使用Spring Boot实现MySQL的读写分离可以通过配置多个数据源,并在不同的服务中处理读写操作。下面是一个简单的示例:

  1. 配置application.properties文件:
# 主数据源
spring.datasource.master.url=jdbc:mysql://localhost:3306/masterdb
spring.datasource.master.username=root
spring.datasource.master.password=root

# 从数据源
spring.datasource.slave.url=jdbc:mysql://localhost:3306/slavedb
spring.datasource.slave.username=root
spring.datasource.slave.password=root
  1. 创建两个数据源的配置类:
@Configuration
public class DataSourceConfig {
    
    @Primary
    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "routingDataSource")
    public AbstractRoutingDataSource routingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
                                                        @Qualifier("slaveDataSource") DataSource slaveDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("master", masterDataSource);
        targetDataSources.put("slave", slaveDataSource);

        RoutingDataSource routingDataSource = new RoutingDataSource();
        routingDataSource.setTargetDataSources(targetDataSources);
        routingDataSource.setDefaultTargetDataSource(masterDataSource);

        return routingDataSource;
    }
}
  1. 创建一个自定义的RoutingDataSource类:
public class RoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSource();
    }
}
  1. 创建一个DataSourceContextHolder类用于切换数据源:
public class DataSourceContextHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void setDataSource(String dataSource) {
        contextHolder.set(dataSource);
    }

    public static String getDataSource() {
        return contextHolder.get();
    }

    public static void clearDataSource() {
        contextHolder.remove();
    }
}
  1. 在需要切换数据源的地方调用DataSourceContextHolder.setDataSource(“master”)或DataSourceContextHolder.setDataSource(“slave”)来切换数据源。

通过以上步骤,可以实现Spring Boot中的MySQL读写分离配置。

0