当前位置: 移动技术网 > IT编程>开发语言>Java > springboot基于Mybatis mysql实现读写分离

springboot基于Mybatis mysql实现读写分离

2019年07月19日  | 移动技术网IT编程  | 我要评论

近日工作任务较轻,有空学习学习技术,遂来研究如果实现读写分离。这里用博客记录下过程,一方面可备日后查看,同时也能分享给大家(网上的资料真的大都是抄来抄去,,还不带格式的,看的真心难受)。

完整代码:https://github.com/fleyx/demo-project/tree/master/dxfl

1、背景

一个项目中数据库最基础同时也是最主流的是单机数据库,读写都在一个库中。当用户逐渐增多,单机数据库无法满足性能要求时,就会进行读写分离改造(适用于读多写少),写操作一个库,读操作多个库,通常会做一个数据库集群,开启主从备份,一主多从,以提高读取性能。当用户更多读写分离也无法满足时,就需要分布式数据库了(可能以后会学习怎么弄)。

正常情况下读写分离的实现,首先要做一个一主多从的数据库集群,同时还需要进行数据同步。这一篇记录如何用 mysql 搭建一个一主多次的配置,下一篇记录代码层面如何实现读写分离。

2、搭建一主多从数据库集群

主从备份需要多台虚拟机,我是用 wmware 完整克隆多个实例,注意直接克隆的虚拟机会导致每个数据库的 uuid 相同,需要修改为不同的 uuid。

•主库配置

主数据库(master)中新建一个用户用于从数据库(slave)读取主数据库二进制日志,sql 语句如下:

mysql> create user 'repl'@'%' identified by '123456';#创建用户
mysql> grant replication slave on *.* to 'repl'@'%';#分配权限
mysql>flush privileges; #刷新权限

同时修改 mysql 配置文件开启二进制日志,新增部分如下:

[mysqld]
server-id=1
log-bin=master-bin
log-bin-index=master-bin.index

然后重启数据库,使用show master status;语句查看主库状态,如下所示:


•从库配置

同样先新增几行配置:

[mysqld]
server-id=2
relay-log-index=slave-relay-bin.index
relay-log=slave-relay-bin

然后重启数据库,使用如下语句连接主库:

change master to
  master_host='192.168.226.5',
  master_user='root',
  master_password='123456',
  master_log_file='master-bin.000003',
  master_log_pos=154;

接着运行start slave;开启备份,正常情况如下图所示:slave_io_running 和 slave_sql_running 都为 yes。

可以用这个步骤开启多个从库。

默认情况下备份是主库的全部操作都会备份到从库,实际可能需要忽略某些库,可以在主库中增加如下配置:

# 不同步哪些数据库
binlog-ignore-db = mysql
binlog-ignore-db = test
binlog-ignore-db = information_schema
# 只同步哪些数据库,除此之外,其他不同步
binlog-do-db = game

3、代码层面进行读写分离

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

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

1)、如何切换数据源

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

2)、如何选择数据源

事务一般是注解在 service 层的,因此在开始这个 service 方法调用时要确定数据源,有什么通用方法能够在开始执行一个方法前做操作呢?相信你已经想到了那就是切面 。怎么切有两种办法:
•注解式,定义一个只读注解,被该数据标注的方法使用读库
•方法名,根据方法名写切点,比如 getxxx 用读库,setxxx 用写库

3)、代码编写

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

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

mysql:
 datasource:
 #读库数目
 num: 1
 type-aliases-package: com.example.dxfl.dao
 mapper-locations: classpath:/mapper/*.xml
 config-location: classpath:/mybatis-config.xml
 write:
 url: jdbc:mysql://192.168.226.5:3306/test?useunicode=true&characterencoding=utf-8&usessl=true
 username: root
 password: 123456
 driver-class-name: com.mysql.jdbc.driver
 read:
 url: jdbc:mysql://192.168.226.6:3306/test?useunicode=true&characterencoding=utf-8&usessl=true
 username: root
 password: 123456
 driver-class-name: com.mysql.jdbc.driver

b、编写 dbcontextholder 类

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

/**
 * description 这里切换读/写模式
 * 原理是利用threadlocal保存当前线程是否处于读模式(通过开始read_only注解在开始操作前设置模式为读模式,
 * 操作结束后清除该数据,避免内存泄漏,同时也为了后续在该线程进行写操作时任然为读模式
 * @author fxb
 * @date 2018-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()方法获取当前操作类别,同时可进行读库的负载均衡,代码如下:

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 == dbcontextholder.write) {
  log.info("使用了写库");
  return typekey;
 }
 //使用随机数决定使用哪个读库
 int sum = numberutil.getrandom(1, num);
 log.info("使用了读库{}", sum);
 return dbcontextholder.read + sum;
 }
}

d、编写配置类

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

@configurproperties 自动生成数据源:
 /**
 * 写数据源
 *
 * @primary 标志这个 bean 如果在多个同类 bean 候选时,该 bean 优先被考虑。
 * 多数据源配置的时候注意,必须要有一个主数据源,用 @primary 标志该 bean
 */
 @primary
 @bean
 @configurationproperties(prefix = "mysql.datasource.write")
 public datasource writedatasource() {
 return new druiddatasource();
 }

读数据源类似,注意有多少个读库就要设置多少个读数据源,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

 /**
 * 多数据源需要自己设置sqlsessionfactory
 */
 @bean
 public sqlsessionfactory sqlsessionfactory() throws exception {
 sqlsessionfactorybean bean = new sqlsessionfactorybean();
 bean.setdatasource(routingdatasource());
 resourcepatternresolver resolver = new pathmatchingresourcepatternresolver();
 // 实体类对应的位置
 bean.settypealiasespackage(typealiasespackage);
 // mybatis的xml的配置
 bean.setmapperlocations(resolver.getresources(mapperlocation));
 bean.setconfiglocation(resolver.getresource(configlocation));
 return bean.getobject();
 }

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

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

4)、选择数据源

多数据源配置好了,但是代码层面如何选择选择数据源呢?这里介绍两种办法:

a、注解式

首先定义一个只读注解,被这个注解方法使用读库,其他使用写库,如果项目是中途改造成读写分离可使用这个方法,无需修改业务代码,只要在只读的 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;
 }
}

b、方法名式

这种方法不许要注解,但是需要service中方法名称按一定规则编写,然后通过切面来设置数据库类别,比如setxxx设置为写、getxxx设置为读,代码我就不写了,应该都知道怎么写。

4、测试

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

测试结果

读写分离只是数据库扩展的一个临时解决办法,并不能一劳永逸,随着负载进一步增大,只有一个库用于写入肯定是不够的,而且单表的数据库是有上限的,mysql 最多千万级别的数据能保持较好的查询性能。最终还是会变成--分库分表架构的。

总结

以上所述是小编给大家介绍的springboot基于mybatis mysql实现读写分离,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网