数据库系列——基于MySQL主从同步实现读写分离

前提

搭建一主多从数据库集群 参考上一篇文章   https://blog.csdn.net/Coder_Boy_/article/details/110950347

本文Github代码地址:https://github.com/cheriduk/spring-boot-integration-template

本文核心:代码层面进行读写分离

代码环境是springboot+mybatis+druib连接池。想要读写分离就需要配置多个数据源,在进行写操作是选择写的数据源,读操作时选择读的数据源。其中有两个关键点:

  1. 如何切换数据源
  2. 如何根据不同的方法选择正确的数据源

1)、如何切换数据源

通常用springboot时都是使用它的默认配置,只需要在配置文件中定义好连接属性就行了,但是现在我们需要自己来配置了,spring是支持多数据源的,多个datasource放在一个HashMapTargetDataSource中,通过dertermineCurrentLookupKey获取key来觉定要使用哪个数据源。因此我们的目标就很明确了,建立多个datasource放到TargetDataSource中,同时重写dertermineCurrentLookupKey方法来决定使用哪个key。

2)、如何选择数据源

事务一般是注解在Service层的,因此在开始这个service方法调用时要确定数据源,有什么通用方法能够在开始执行一个方法前做操作呢?相信你已经想到了那就是切面 。怎么切有两种办法:

  • 注解式,定义一个只读注解,被该数据标注的方法使用读库
  • 方法名,根据方法名写切点,比如getXXX用读库,setXXX用写库

3)、代码编写

项目目录结构:

a、编写配置文件,配置两个数据源信息

只有必填信息,其他都用默认设置

application.properties

mysql.datasource.config-location=classpath:/mybatis-config.xml
mysql.datasource.mapper-locations=classpath:/mapper/*.xml
mysql.datasource.num=2

mysql.datasource.read1.driverClass=com.mysql.jdbc.Driver
mysql.datasource.read1.password=123456
mysql.datasource.read1.url=jdbc:mysql://127.0.0.1:3307/test?serverTimezone=Asia/Shanghai
mysql.datasource.read1.username=root

mysql.datasource.read2.driverClass=com.mysql.jdbc.Driver
mysql.datasource.read2.password=123456
mysql.datasource.read2.url=jdbc:mysql://127.0.0.1:3308/test?serverTimezone=Asia/Shanghai
mysql.datasource.read2.username=root


mysql.datasource.write.driverClass=com.mysql.jdbc.Driver
mysql.datasource.write.password=123456
mysql.datasource.write.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai
mysql.datasource.write.username=root

b、编写DbContextHolder类

这个类用来设置数据库类别,其中有一个ThreadLocal用来保存每个线程的是使用读库,还是写库。代码如下:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description 这里切换读/写模式
 * 原理是利用ThreadLocal保存当前线程是否处于读模式(通过开始READ_ONLY注解在开始操作前设置模式为读模式,
 * 操作结束后清除该数据,避免内存泄漏,同时也为了后续在该线程进行写操作时任然为读模式
 *
 * @author 杜康
 * @date 2020-08-31
 */
public class DbContextHolder {

    private static Logger log = LoggerFactory.getLogger(DbContextHolder.class);
    public static final String WRITE = "write";
    public static final String READ = "read";

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

    public static void setDbType(String dbType) {
        if (dbType == null) {
            log.error("dbType为空");
            throw new NullPointerException();
        }
        log.info("设置dbType为:{}",dbType);
        contextHolder.set(dbType);
    }

    public static String getDbType() {
        return contextHolder.get() == null ? WRITE : contextHolder.get();
    }

    public static void clearDbType() {
        contextHolder.remove();
    }
}

c、重写determineCurrentLookupKey方法

spring在开始进行数据库操作时会通过这个方法来决定使用哪个数据库,因此我们在这里调用上面DbContextHolder类的getDbType()方法获取当前操作类别,同时可进行读库的负载均衡,代码如下

package com.gary.dbrw.datachange;

import com.gary.dbrw.util.NumberUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class MyAbstractRoutingDataSource extends AbstractRoutingDataSource {

    @Value("${mysql.datasource.num}")
    private int num;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DbContextHolder.getDbType();
        if (typeKey.equals(DbContextHolder.WRITE)) {
            log.info("使用了写库w");
            return typeKey;
        }
        //使用随机数决定使用哪个读库(可写负载均衡算法)
        int sum = NumberUtil.getRandom(1, num);
        log.info("使用了读库r{}", sum);
        return DbContextHolder.READ + sum;
    }
}

d、编写配置类

由于要进行读写分离,不能再用springboot的默认配置,我们需要手动来进行配置。首先生成数据源,使用@ConfigurProperties自动生成数据源:

package com.gary.dbrw.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.gary.dbrw.common.Properties;
import com.gary.dbrw.datachange.DbContextHolder;
import com.gary.dbrw.datachange.MyAbstractRoutingDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
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.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@MapperScan(basePackages = "com.gary.dbrw.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
@Configuration
public class DataSourceConfig {

//    @Value("${mysql.datasource.type-aliases-package}")
//    private String typeAliasesPackage;
//
//    @Value("${mysql.datasource.mapper-locations}")
//    private String mapperLocation;
//
//    @Value("${mysql.datasource.config-location}")
//    private String configLocation;

    /**
     * 写数据源
     *
     * @Primary 标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。
     * 多数据源配置的时候注意,必须要有一个主数据源,用 @Primary 标志该 Bean
     */
    @Primary
    @Bean
    @ConfigurationProperties(prefix = "mysql.datasource.write")
    public DataSource writeDataSource() {
        return new DruidDataSource();
    }

    /**
     * 读数据源
     */
    @Bean
    @ConfigurationProperties(prefix = "mysql.datasource.read1")
    public DataSource read1() {
        return new DruidDataSource();
    }


    /**
     * 多数据源需要自己设置sqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(routingDataSource());
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 实体类对应的位置
        bean.setTypeAliasesPackage(Properties.typeAliasesPackage);
        // mybatis的XML的配置
        bean.setMapperLocations(resolver.getResources(Properties.mapperLocation));
        bean.setConfigLocation(resolver.getResource(Properties.configLocation));
        return bean.getObject();
    }

    /**
     * 设置事务,事务需要知道当前使用的是哪个数据源才能进行事务处理
     */
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(routingDataSource());
    }

    /**
     * 设置数据源路由,通过该类中的determineCurrentLookupKey决定使用哪个数据源
     */
    @Bean
    public AbstractRoutingDataSource routingDataSource() {
        MyAbstractRoutingDataSource proxy = new MyAbstractRoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DbContextHolder.WRITE, writeDataSource());
        targetDataSources.put(DbContextHolder.READ + "1", read1());
        proxy.setDefaultTargetDataSource(writeDataSource());
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }

}

注意有多少个读库就要设置多少个读数据源,Bean名为read+序号。

最后设置数据源,使用的是我们之前写的MyAbstractRoutingDataSource类

  /**
     * 设置数据源路由,通过该类中的determineCurrentLookupKey决定使用哪个数据源
     */
    @Bean
    public AbstractRoutingDataSource routingDataSource() {
        MyAbstractRoutingDataSource proxy = new MyAbstractRoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DbContextHolder.WRITE, writeDataSource());
        targetDataSources.put(DbContextHolder.READ + "1", read1());
        proxy.setDefaultTargetDataSource(writeDataSource());
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }

接着需要设置sqlSessionFactory,配置MyBatis的sqlSessionFactoryRef 引用

 /**
     * 多数据源需要自己设置sqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(routingDataSource());
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 实体类对应的位置
        bean.setTypeAliasesPackage(Properties.typeAliasesPackage);
        // mybatis的XML的配置
        bean.setMapperLocations(resolver.getResources(Properties.mapperLocation));
        bean.setConfigLocation(resolver.getResource(Properties.configLocation));
        return bean.getObject();
    }
@MapperScan(basePackages = "com.gary.dbrw.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
@Configuration
public class DataSourceConfig {
   
   

最后还得配置下事务,否则事务不生效

 /**
     * 设置事务,事务需要知道当前使用的是哪个数据源才能进行事务处理
     */
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(routingDataSource());
    }

4)、选择数据源

多数据源配置好了,但是代码层面如何选择选择数据源呢?

采用现在流行的注解加切面。

首先定义一个只读注解,被这个注解方法使用读库,其他使用写库,如果项目是中途改造成读写分离可使用这个方法,无需修改业务代码,只要在只读的service方法上加一个注解即可。


@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReadOnly {
}

然后写一个切面来切换数据使用哪种数据源,重写getOrder保证本切面优先级高于事务切面优先级,(这样才可以使用事务)在启动类加上@EnableTransactionManagement(order = 10),为了代码如下:

@Aspect
@Component
public class ReadOnlyInterceptor implements Ordered {
    private static final Logger log = LoggerFactory.getLogger(ReadOnlyInterceptor.class);

    @Around("@annotation(readOnly)")
    public Object setRead(ProceedingJoinPoint joinPoint, ReadOnly readOnly) throws Throwable {
        try {
            DbContextHolder.setDbType(DbContextHolder.READ);
            return joinPoint.proceed();
        } finally {
            //清楚DbType一方面为了避免内存泄漏,更重要的是避免对后续在本线程上执行的操作产生影响
            DbContextHolder.clearDbType();
            log.info("清除threadLocal");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

配置测试类:


@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    StudentMapper studentMapper;

    @ReadOnly
    @Override
    public List<Student> selectAllList() {
        return studentMapper.selectAll();
    }


    @Override
    public int addOneStudent(Student student) {
        return studentMapper.insertSelective(student);
    }
}
@RestController
@RequestMapping("user")
public class StudentController {

    @Resource
    StudentService studentService;

    @GetMapping("/testRW")
    public String DbRead(Integer dbType) {
        System.out.println("dbType=:" + dbType);
        List<Student> students = studentService.selectAllList();
        return "ReadDB=>" + students;
    }

    @PostMapping("/testRW")
    public String DbWrite(Student student) {
        int count = studentService.addOneStudent(student);
        return "Wr DB=>" + count;
    }
}

4、测试验证

编写好代码来试试结果如何,下面是运行截图:


数据库变化查看:


猜你喜欢

转载自blog.csdn.net/Coder_Boy_/article/details/111036260