Mysql 读写分离插件简化版

Posted lisin-lee-cooper

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql 读写分离插件简化版相关的知识,希望对你有一定的参考价值。

一.原理

1.基于互联网背景,服务响应需要越来越快,从而衍生出读写分离,即让主数据库(master)处理事务性增、改、删操作(INSERT、UPDATE、DELETE),而从数据库(slave)处理SELECT查询操作;

2.避免慢查询长期占用链接,导致插入时变慢;或者避免插入时过慢影响查询速度;

3.主数据库只做修改,从服务器只做查询,同时主服务器的修改需要同步到从服务器。

4.服务启动时,配置好主从数据源,执行方法时根据注解ReadOnly选择从库(读库)数据源,默认选择主库(修改)数据源。

二代码框架

1.工程结构
mysql读写分离插件代码结构

2.读数据库注解定义

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

}

3.数据库名称本地线程池设置

public class DbContextHolder {

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

    public static void setDbContext(String dbName) {
        if (dbName == null || "".equals(dbName)) {
            throw new NullPointerException();
        }
        contextHolder.set(dbName);
    }

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

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

}

4.动态数据源选择类

public class RoutingDataSource extends AbstractRoutingDataSource {

    private static final Logger LOG = LoggerFactory.getLogger(DBRouterAop.class);

    @Override
    public DataSource determineTargetDataSource() {
        return super.determineTargetDataSource();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String dbName = DbContextHolder.getDbContext();
        LOG.info("target database source is " + (dbName == null ? "default datasource" : dbName));
        return dbName;
    }
}

5.数据源配置类

@Configuration
public class DataSourceConfig {

    @Autowired
    @Qualifier("master")
    private DbProperties master;

    @Autowired
    @Qualifier("slave")
    private DbProperties slave;

    @Bean
    public RoutingDataSource routingDataSource() {

        RoutingDataSource routingDataSource = new RoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        //master
        DataSource masterDatasource = getDataSource(master);
        targetDataSources.put(DbType.MASTER.name(), masterDatasource);
        routingDataSource.setDefaultTargetDataSource(masterDatasource);

        //slave
        DataSource slaveDatasource = getDataSource(slave);
        targetDataSources.put(DbType.SLAVE.name(), slaveDatasource);

        routingDataSource.setTargetDataSources(targetDataSources);
        routingDataSource.afterPropertiesSet();

        return routingDataSource;
    }

    private DataSource getDataSource(DbProperties properties) {
        return new DriverManagerDataSource(properties.getUrl(), properties.getUsername(), properties.getPassword());
    }
}

6.切面选择方法执行时选择的数据源

@Aspect
@Component
public class DBRouterAop {

    @Around(value = "@annotation(readOnly)")
    public Object proceed(ProceedingJoinPoint pjp, ReadOnly readOnly) throws Throwable {
        try {
            DbContextHolder.setDbContext(DbType.SLAVE.name());
            Object result = pjp.proceed();
            return result;
        } finally {
            DbContextHolder.removeDbContext();
        }
    }
}

7.pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>datasource-router-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
        <relativePath/>
    </parent>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.7</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.1</version>
                <configuration>
                    <attach>true</attach>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>


</project>

三.测试验证

1.依赖读写分离插件

   <dependency>
            <groupId>org.example</groupId>
            <artifactId>datasource-router-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
   </dependency>

2.配置数据源

server:
  port: 8081

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:/mybatis/mapper/*.xml
  type-aliases-package: com.example.test.infrastructure.po.User

# 数据库配置
db:
  master:
    url: jdbc:mysql://127.0.0.1:3306/master?useUnicode=true
    username: root
    password: root123
  slave:
    url: jdbc:mysql://127.0.0.1:3306/slave?useUnicode=true
    username: root
    password: root123

3.结果验证

1.查询时数据源选择的时从库
从库查询

2.写入时数据源选择主库

主库写入

以上是关于Mysql 读写分离插件简化版的主要内容,如果未能解决你的问题,请参考以下文章

应用MySQL读写分离以提高MySQL服务器的读写性能

轻松实现MySQL读写分离

mysql数据库多种备份及读写分离搭建

Sharding-JDBC自动实现MySQL读写分离

MMM架构实现MySQL高可用读写分离(进阶版,包含Amoeba)

mysq通过ProxySQL实现读写分离