1. 引言
读写分离要做的事情就是对于一条SQL该选择哪个数据库去执行,至于谁来做选择数据库这件事儿,无非两个,要么中间件帮我们做,要么程序自己做。因此,一般来讲,读写分离有两种实现方式。第一种是依靠中间件(比如:MyCat),也就是说应用程序连接到中间件,中间件帮我们做SQL分离;第二种是应用程序自己去做分离。这里我们选择程序自己来做,主要是利用Spring提供的路由数据源,以及AOP
然而,应用程序层面去做读写分离最大的弱点(不足之处)在于无法动态增加数据库节点,因为数据源配置都是写在配置中的,新增数据库意味着新加一个数据源,必然改配置,并重启应用。当然,好处就是相对简单。
读写分离示意图
2. AbstractRoutingDataSource
基于特定的查找key路由到特定的数据源。它内部维护了一组目标数据源,并且做了路由key与目标数据源之间的映射,提供基于key查找数据源的方法。
AbstractRoutingDataSource
3. 实践
3.1 添加依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.lovingliu</groupId>
<artifactId>example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.2 数据源的配置
application.yml
server:
port: 1000
spring:
datasource:
master:
jdbc-url: jdbc:mysql://192.0.0.134:3306/dev
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
slave:
jdbc-url: jdbc:mysql://192.0.0.113:3306/dev
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: cn.lovingliu.example.pojo
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
多数据源配置cn.lovingliu.example.config.DataSourceConfig
package cn.lovingliu.example.config;
import cn.lovingliu.example.component.MyRoutingDataSource;
import cn.lovingliu.example.enums.DBTypeEnum;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @Author:LovingLiu
* @Description: SpringBoot 数据源配置
* @Date:Created in 2020-01-09
*/
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.slave")
public DataSource slaveDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
@Qualifier("slaveDataSource") DataSource slaveDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DBTypeEnum.MASTER, masterDataSource);
targetDataSources.put(DBTypeEnum.SLAVE, slaveDataSource);
MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
myRoutingDataSource.setDefaultTargetDataSource(masterDataSource);
myRoutingDataSource.setTargetDataSources(targetDataSources);
return myRoutingDataSource;
}
}
这里,我们配置了3个数据源,1个master,1个slave,1个路由数据源。前2个数据源都是为了生成第3个数据源,而且后续我们只用这最后一个路由数据源。
MyBatis配置cn.lovingliu.example.config.MyBatisTransactionConfig
package cn.lovingliu.example.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.sql.DataSource;
/**
* @Author:LovingLiu
* @Description: 为事务管理器和MyBatis手动指定一个明确的数据源
* @Date:Created in 2020-01-09
*/
@EnableTransactionManagement
@Configuration
public class MyBatisTransactionConfig {
@Resource(name = "myRoutingDataSource")
private DataSource myRoutingDataSource;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(myRoutingDataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new DataSourceTransactionManager(myRoutingDataSource);
}
}
由于Spring容器中现在有3个数据源,所以我们需要为事务管理器和MyBatis手动指定一个明确的数据源
3.3. 设置路由key / 查找数据源
目标数据源就是那前2个这个我们是知道的,但是使用的时候是如果查找数据源的呢?
首先,我们定义一个枚举来代表这两个数据源
cn.lovingliu.example.enums.DBTypeEnum
package cn.lovingliu.example.enums;
/**
* @Author:LovingLiu
* @Description: 设置路由key / 查找数据源
* @Date:Created in 2020-01-09
*/
public enum DBTypeEnum {
MASTER, SLAVE;
}
接下来,通过ThreadLocal
将数据源设置到每个线程上下文中
cn.lovingliu.example.component.DBContextHolder
package cn.lovingliu.example.component;
import cn.lovingliu.example.enums.DBTypeEnum;
/**
* @Author:LovingLiu
* @Description: 通过ThreadLocal将数据源设置到每个线程上下文中
* @Date:Created in 2020-01-09
*/
public class DBContextHolder {
private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();
public static void set(DBTypeEnum dbType) {
contextHolder.set(dbType);
}
public static DBTypeEnum get() {
return contextHolder.get();
}
public static void master() {
set(DBTypeEnum.MASTER);
System.out.println("切换到master");
}
public static void slave() {
set(DBTypeEnum.SLAVE);
System.out.println("切换到slave");
}
}
获取路由key
cn.lovingliu.example.component.MyRoutingDataSource
package cn.lovingliu.example.component;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.lang.Nullable;
/**
* @Author:LovingLiu
* @Description:
* @Date:Created in 2020-01-09
*/
public class MyRoutingDataSource extends AbstractRoutingDataSource {
@Nullable
@Override
protected Object determineCurrentLookupKey() {
return DBContextHolder.get();
}
}
设置路由key
默认情况下,所有的查询都走从库,插入/修改/删除走主库。我们通过方法名来区分操作类型(CRUD)
cn.lovingliu.example.aop.DataSourceAop
package cn.lovingliu.example.aop;
import cn.lovingliu.example.component.DBContextHolder;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* @Author:LovingLiu
* @Description: 通过方法名来区分操作类型
* @Date:Created in 2020-01-09
*/
@Component
@Aspect
public class DataSourceAop {
@Pointcut("!@annotation(cn.lovingliu.example.annotation.Master) " +
"&& (execution(* cn.lovingliu.example.service..*.select*(..)) " +
"|| execution(* cn.lovingliu.example.service.*.get*(..)))")
public void readPointcut() {
}
@Pointcut("@annotation(cn.lovingliu.example.annotation.Master) " +
"|| execution(* cn.lovingliu.example.service..*.insert*(..)) " +
"|| execution(* cn.lovingliu.example.service..*.add*(..)) " +
"|| execution(* cn.lovingliu.example.service..*.update*(..)) " +
"|| execution(* cn.lovingliu.example.service..*.edit*(..)) " +
"|| execution(* cn.lovingliu.example.service..*.delete*(..)) " +
"|| execution(* cn.lovingliu.example.service..*.remove*(..))")
public void writePointcut() {
}
@Before("readPointcut()")
public void read() {
DBContextHolder.slave();
}
@Before("writePointcut()")
public void write() {
DBContextHolder.master();
}
}
有一般情况就有特殊情况,特殊情况是某些情况下我们需要强制读主库,针对这种情况,我们定义一个主键,用该注解标注的就读主库
cn.lovingliu.example.annotation.Master
package cn.lovingliu.example.annotation;
/**
* @Author:LovingLiu
* @Description: 强制读主库
* @Date:Created in 2020-01-09
*/
public @interface Master {
}
4. 测试
cn.lovingliu.example.service.impl.StuServiceImplTest
package cn.lovingliu.example.service.impl;
import cn.lovingliu.example.pojo.Stu;
import cn.lovingliu.example.service.StuService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* @Author:LovingLiu
* @Description: 测试
* @Date:Created in 2020-01-09
*/
@RunWith(SpringRunner.class)
@SpringBootTest
class StuServiceImplTest {
@Autowired
private StuService stuService;
@Test
void insert() {
Stu stu = new Stu();
stu.setAge(18);
stu.setName("lili");
int count = stuService.insert(stu);
System.out.println("count: "+count);
}
@Test
void save() {
}
@Test
void selectAll() {
List<Stu> list = stuService.selectAll();
System.out.println("学生人数:"+list.size());
}
@Test
void getToken() {
}
}
实现读写分离
本文来自https://www.cnblogs.com/cjsblog/p/9712457.html,并成功实现读写分离
网友评论