多数据源和动态数据源的区别?
多数据源:可以根据业务需求访问不同的数据,指定对应的策略:查询,增加,删除,修改操作访问对应数据,不同数据库做好的数据一致性的处理。这个比较好理解。
动态数据源:根据配置的文件,业务动态切换访问的数据库:一般是通过 Spring 的AOP,AspactJ来实现动态织入,通过编程继承实现Spring 中的 AbstractRoutingDataSource 来实现数据库访问的动态切换,不仅可以方便扩展,不影响现有程序,而且对于此功能的增删也比较容易。动态数据源也包括了多数据源。
mycat 实现读写分离:使用 mycat 提供的读写分离功能,mycat连接多个数据库,数据源只需要连接mycat,mycat 会根据路由规则自动转发到对应的数据库上,对于开发人员而言他还是连接了一个数据库(实际是 mysql 的mycat中间件),而且也不需要根据不同业务来选择不同的库,这样就不会有多余的代码产生。
一般来说,实现的原理是:在项目中配置两个数据源,分别是只读和写的数据源,使用 Spring 的 AOP 技术拦截业务逻辑层的方法名的前缀,如果前缀为设置好的比如 select、get、find、query等,就切换到只读的数据源。其它的就切换到写的数据源。也可以自己定义注解进行封装。
在 Spring 2.0 引入了 AbstractRoutingDataSource,该类充当了 DataSource 的路由中介,能有在运行时根据某种key值来动态切换到真正的DataSource上。
OK,我们创建一个 SpringBoot 项目:MycatTest,项目结构图如下:
1、pom.xml 配置内容如下:
<?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>com.study</groupId>
<artifactId>MycatTest</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
</parent>
<dependencies>
<!--Spring boot 集成包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--web支持-->
<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>
<!-- 引入 AOP 切面依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 数据库MySQL 依赖包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- mybatis 依赖包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- 该 starter 会扫描配置文件中的 DataSource,然后自动创建使用该 DataSource 的 SqlSessionFactoryBean,并注册到 Spring 上下文中 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- 阿里巴巴的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<!-- 阿里巴巴 fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2、bootstrap.yml 配置文件
spring:
application:
name: MycatTest
datasource:
type: com.alibaba.druid.pool.DruidDataSource
# 自定义只读的数据源
read-only-source:
# 对应 mycat 的数据库地址
jdbc-url: jdbc:mysql://127.0.0.1:8066/mycatSchemaDB
driver-class-name: com.mysql.jdbc.Driver
username: user
password: user
# 自定义可写的数据源
write-source:
jdbc-url: jdbc:mysql://127.0.0.1:8066/mycatSchemaDB
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
server:
port: 8080
# 将SpringBoot项目作为单实例部署调试时,不需要注册到注册中心
eureka:
client:
fetch-registry: false
register-with-eureka: false
# mybatis 配置
mybatis:
# Mybatis扫描的mapper文件
mapper-locations: classpath:mapper/*.xml
# 扫描哪个包下的对象
type-aliases-package: com.study.entity
# Mybatis配置文件
config-location: classpath:mybatis-config.xml
3、在 resource 包下创建文件:mybatis-config.xml,这是 mybatis 的全局配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局配置参数 -->
<settings>
<!-- 使全局的映射器启用或禁用缓存。 -->
<setting name="cacheEnabled" value="true"/>
<!-- debug 模式打印 sql 语句 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>
4、在 resource 包下创建 mapper 目录,用于存放 mybatis 与数据库的映射文件,然后创建 UsertEntityMapper.xml 文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.study.dao.UserDao">
<resultMap id="BaseResultMap" type="com.study.entity.UserEntity">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
</resultMap>
<!-- 新增用户信息 -->
<insert id="addUser" parameterType="com.study.entity.UserEntity">
insert into t_user (id,user_name)
values (null,#{userName,jdbcType=VARCHAR})
</insert>
<!-- 查询所有用户信息 -->
<select id="findAllUsers" resultMap="BaseResultMap">
select id, user_name
from t_user
</select>
</mapper>
注意:这里的 namespace 对应 DAO 层的接口全路径,BaseResultMap 对应实体的全路径。
5、entity 包下创建 UserEntity 实体类,内容如下:
package com.study.entity;
/**
* @author biandan
* @description
* @signature 让天下没有难写的代码
* @create 2021-04-26 上午 12:10
*/
public class UserEntity {
private Integer id;
private String userName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
6、在 dao 包下创建接口 UserDao,内容如下:注意需要增加 @Mapper 注解,标注为 Mybatis 的映射文件,如果不想在每个 dao 的接口上加入此注解,也可以在启动类上加上扫描的包。下面会提到。
package com.study.dao;
import com.study.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author biandan
* @description
* @signature 让天下没有难写的代码
* @create 2021-04-26 上午 12:14
*/
@Mapper
public interface UserDao {
/**
* 查询所有用户
* @return
*/
List<UserEntity> findAllUsers();
/**
* 新增用户信息
* @param userEntity
* @return
*/
int addUser(UserEntity userEntity);
}
7、业务层 service 包下创建类 UserService,内容如下 :
package com.study.service;
import com.study.dao.UserDao;
import com.study.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author biandan
* @description
* @signature 让天下没有难写的代码
* @create 2021-04-26 上午 12:12
*/
@Service
public class UserService {
@Autowired
private UserDao userDao;
/**
* 查询所有用户信息
* @return
*/
public List<UserEntity> findAllUsers(){
return userDao.findAllUsers();
}
/**
* 增加用户信息
* @param userEntity
* @return
*/
public Integer addUser(UserEntity userEntity){
return userDao.addUser(userEntity);
}
}
8、controller 层创建类 UserController,内容如下:
package com.study.controller;
import com.study.entity.UserEntity;
import com.study.service.UserService;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author biandan
* @description
* @signature 让天下没有难写的代码
* @create 2021-04-26 上午 12:27
*/
@RestController
public class UserController {
@Autowired
private UserService userService;
/**
* 查询所有用户信息
*
* @return
*/
@RequestMapping(value = "/findAllUsers", method = RequestMethod.GET)
public List<UserEntity> findAllUsers() {
return userService.findAllUsers();
}
/**
* 新增用户信息
*
* @param userName
* @return
*/
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public Boolean addUser(String userName) {
UserEntity userEntity = new UserEntity();
userEntity.setUserName(userName);
if (userService.addUser(userEntity) > 0) {
return true;
}
return false;
}
}
9、启动类 MycatApplication 如下:注意这里可以增加 @MapperScan 扫描 DAO 层包,这样就不用在每个 dao 的接口上增加 @Mapper 注解了。
package com.study;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//在启动的类加上:@MapperScan("com.study.dao") 注解,这样就不需要在每个 Dao 类里加入注解 @Mapper 了。
//@MapperScan("com.study.dao")
public class MycatApplication {
public static void main(String[] args) {
SpringApplication.run(MycatApplication.class,args);
}
}
OK,到这里就是我们就创建了最简单的 SpringBoot 整合 Mybatis 的项目,可以实现简单的 CRUD 逻辑。但是我们现在引用 Mycat,还要实现动态数据源的切换,以及读写分离,因此,还需要配置写信息。
10、首先配置数据源,我们在 config 包下创建配置类:DataSourceConfig,这个配置类就是使用 Spring 的 IoC、DI 的思想,内容如下:
package com.study.config;
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;
/**
* @author biandan
* @description 数据源配置
* @signature 让天下没有难写的代码
* @create 2021-04-26 上午 12:34
*/
@Configuration
public class DataSourceConfig {
//创建只读数据源
@Bean(name = "readOnlySource")
//application.yml 中对应只读属性的前缀
@ConfigurationProperties(prefix = "spring.datasource.read-only-source")
public DataSource readOnlySource(){
return DataSourceBuilder.create().build();
}
//创建可写数据源
@Bean(name = "writeSource")
//application.yml 中对应可写属性的前缀
@ConfigurationProperties(prefix = "spring.datasource.write-source")
public DataSource writeSource(){
return DataSourceBuilder.create().build();
}
}
11、创建 DataSourceContextHolder 配置类,使用 ThreadLocal 将数据源保存到服务器本地,代码如下:
package com.study.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
/**
* @author biandan
* @description 将数据源保存到本地
* @signature 让天下没有难写的代码
* @create 2021-04-26 上午 1:07
*/
@Configuration
@Lazy(false)//【饿汉模式】禁止懒加载,对象会在系统启动的时候被创建。默认为 true,设置是true就会在使用的时候才创建
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
/**
* 设置数据源
*
* @param dataSource
*/
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
}
/**
* 获取数据源
*
* @return
*/
public static String getDataSource() {
String dataSource = contextHolder.get();
return dataSource;
}
/**
* 当前线程局部变量的值删除,目的是为了减少内存的占用
*/
public static void removeDataSource() {
contextHolder.remove();
System.out.println("*** 删除当前线程局部变量 ***");
}
}
12、创建 DynamicDataSource 配置类,继承 AbstractRoutingDataSource 类,AbstractRoutingDataSource 类能够在运行时,根据 key 来动态的切换到真正的 DataSource 上。
package com.study.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @author biandan
* @description AbstractRoutingDataSource 该类充当了DataSource的路由中介, 能够在运行时, 根据某种key值来动态切换到真正的DataSource上。
* @signature 让天下没有难写的代码
* @create 2021-04-26 上午 1:18
*/
@Configuration
@Primary //自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者
public class DynamicDataSource extends AbstractRoutingDataSource {
@Autowired
@Qualifier("readOnlySource")
private DataSource readOnlySource;
@Autowired
@Qualifier("writeSource")
private DataSource writeSource;
/**
* 这个是主要重写的方法:返回生效的数据源名称
*
* @return
*/
@Override
protected Object determineCurrentLookupKey() {
String dataSource = DataSourceContextHolder.getDataSource();
System.out.println("DynamicDataSource 获取到的 dataSource=" + dataSource);
return dataSource;
}
/***
* 配置数据源信息
*/
@Override
public void afterPropertiesSet() {
Map<Object, Object> map = new HashMap<>();
map.put("readOnlySource",readOnlySource);
map.put("writeSource",writeSource);
setTargetDataSources(map);
setDefaultTargetDataSource(writeSource);//默认数据源
super.afterPropertiesSet();
}
}
13、创建 SwithDataSourceAOP 类,用于实现 Spring 的 AOP 功能,代码如下:
package com.study.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import java.util.Arrays;
import java.util.List;
/**
* @author biandan
* @description 使用AOP动态切换不同的数据源
* @signature 让天下没有难写的代码
* @create 2021-04-26 上午 1:30
*/
@Aspect
@Configuration
@Lazy(false)
@Order(0) //Order设定AOP执行顺序 使之在数据库事务上先执行。定义Spring IOC容器中Bean的执行顺序的优先级。参数值越小优先级越高
public class SwitchDataSourceAOP {
//这里切到我们的方法目录
@Before("execution(* com.study.service.*.*(..))")
public void pointCut(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
if(methodName.startsWith("get") ||methodName.startsWith("find") ||methodName.startsWith("query") ||
methodName.startsWith("select")){
DataSourceContextHolder.setDataSource("readOnlySource");//只读数据源
}else{
DataSourceContextHolder.setDataSource("writeSource");//切换到写的数据源
}
}
}
说明:切面的方法我们自己约定以 get、find、query、select 开头的,都使用只读的数据源,其它的使用写的数据源。
OK,我们来测试一下。先启动 mycat 服务器,然后启动我们的微服务,使用 postman 测试:
1、测试查询功能:http://127.0.0.1:8080/findAllUsers
控制台输出:
2、测试新增用户信息:
控制台输出:
3、我们修改 bootstrap.yml 配置文件,验证 user 用户只读的权限,修改如下:
重启微服务,使用 postman 测试新增功能:
发现使用 user 用户的时候,新增报错了。说明 user 的只读权限不能做新增。验证通过。
本篇博客代码:https://pan.baidu.com/s/1MB3P622O9MlT4sfjqxgtvg 提取码:nzei