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.写入时数据源选择主库

主库写入

三.源码下载

读写分离源码及测试代码下载

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值