Spring boot实现数据库读写分离的方法

 更新时间:2017年01月19日 10:46:22   作者:Srggggg  
本篇文章主要介绍了Spring boot实现数据库读写分离的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

背景

数据库配置主从之后,如何在代码层面实现读写分离?

用户自定义设置数据库路由

Spring boot提供了AbstractRoutingDataSource根据用户定义的规则选择当前的数据库,这样我们可以在执行查询之前,设置读取从库,在执行完成后,恢复到主库。

实现可动态路由的数据源,在每次数据库查询操作前执行

ReadWriteSplitRoutingDataSource.java

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * @author songrgg
 * @since 1.0
 */
public class ReadWriteSplitRoutingDataSource extends AbstractRoutingDataSource {
  @Override
  protected Object determineCurrentLookupKey() {
    return DbContextHolder.getDbType();
  }
}

线程私有路由配置,用于ReadWriteSplitRoutingDataSource动态读取配置

DbContextHolder.java

/**
 * @author songrgg
 * @since 1.0
 */
public class DbContextHolder {
  public enum DbType {
    MASTER,
    SLAVE
  }

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

  public static void setDbType(DbType dbType) {
    if(dbType == null){
      throw new NullPointerException();
    }
    contextHolder.set(dbType);
  }

  public static DbType getDbType() {
    return contextHolder.get() == null ? DbType.MASTER : contextHolder.get();
  }

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

AOP优化代码

利用AOP将设置数据库的操作从代码中抽离,这里的粒度控制在方法级别,所以利用注解的形式标注这个方法涉及的数据库事务只读,走从库。

只读注解,用于标注方法的数据库操作只走从库。

ReadOnlyConnection.java

package com.wallstreetcn.hatano.config;

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

/**
 * Indicates the database operations is bound to the slave database.
 * AOP interceptor will set the database to the slave with this interface.
 * @author songrgg
 * @since 1.0
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReadOnlyConnection {
}

ReadOnlyConnectionInterceptor.java

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * Intercept the database operations, bind database to read-only database as this annotation
 * is applied.
 * @author songrgg
 * @since 1.0
 */
@Aspect
@Component
public class ReadOnlyConnectionInterceptor implements Ordered {

  private static final Logger logger = LoggerFactory.getLogger(ReadOnlyConnectionInterceptor.class);

  @Around("@annotation(readOnlyConnection)")
  public Object proceed(ProceedingJoinPoint proceedingJoinPoint, ReadOnlyConnection readOnlyConnection) throws Throwable {
    try {
      logger.info("set database connection to read only");
      DbContextHolder.setDbType(DbContextHolder.DbType.SLAVE);
      Object result = proceedingJoinPoint.proceed();
      return result;
    } finally {
      DbContextHolder.clearDbType();
      logger.info("restore database connection");
    }
  }

  @Override
  public int getOrder() {
    return 0;
  }
}

UserService.java

@ReadOnlyConnection
public List<User> getUsers(Integer page, Integer limit) {
  return repository.findAll(new PageRequest(page, limit));
}

配置Druid数据库连接池

build.gradle

compile("com.alibaba:druid:1.0.18")

groovy依赖注入

配置dataSource为可路由数据源

context.groovy

import com.alibaba.druid.pool.DruidDataSource
import DbContextHolder
import ReadWriteSplitRoutingDataSource

** SOME INITIALIZED CODE LOAD PROPERTIES **
def dataSourceMaster = new DruidDataSource()
dataSourceMaster.url = properties.get('datasource.master.url')
println("master set to " + dataSourceMaster.url)
dataSourceMaster.username = properties.get('datasource.master.username')
dataSourceMaster.password = properties.get('datasource.master.password')

def dataSourceSlave = new DruidDataSource()
dataSourceSlave.url = properties.get('datasource.slave.url')
println("slave set to " + dataSourceSlave.url)
dataSourceSlave.username = properties.get('datasource.slave.username')
dataSourceSlave.password = properties.get('datasource.slave.password') 
beans {
  dataSource(ReadWriteSplitRoutingDataSource) { bean ->
    targetDataSources = [
        (DbContextHolder.DbType.MASTER): dataSourceMaster,
        (DbContextHolder.DbType.SLAVE): dataSourceSlave
    ]
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 简单介绍java中equals以及==的用法

    简单介绍java中equals以及==的用法

    这篇文章主要介绍了简单介绍java中equals以及==的用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • 详解Java中Collector接口的组成

    详解Java中Collector接口的组成

    今天给大家带来的是关于Java基础的相关知识,文章围绕着Collector接口的组成展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • 浅谈java定时器的发展历程

    浅谈java定时器的发展历程

    这篇文章主要介绍了浅谈java定时器的发展历程,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • java 实现微信服务器下载图片到自己服务器

    java 实现微信服务器下载图片到自己服务器

    这篇文章主要介绍了 java 实现微信服务器下载图片到自己服务器的相关资料,需要的朋友可以参考下
    2017-05-05
  • java  常见位逻辑运算符梳理

    java  常见位逻辑运算符梳理

    这篇文章主要介绍了java常见位逻辑运算符梳理,文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参一下下面文章详细内容
    2022-08-08
  • SpringBoot使用SOFA-Lookout监控的方法

    SpringBoot使用SOFA-Lookout监控的方法

    本文介绍SpringBoot使用蚂蚁金服SOFA-Lookout配合Prometheus进行监控,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-03-03
  • listview点击无效的处理方法(推荐)

    listview点击无效的处理方法(推荐)

    下面小编就为大家带来一篇listview点击无效的处理方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • 深入浅出解析Java ThreadLocal原理

    深入浅出解析Java ThreadLocal原理

    ThreadLocal是JDK包提供的,它提供线程本地变量,如果创建一乐ThreadLocal变量,那么访问这个变量的每个线程都会有这个变量的一个副本,在实际多线程操作的时候,操作的是自己本地内存中的变量,从而规避了线程安全问题,感兴趣的朋友快来看看吧
    2021-11-11
  • java高并发的线程中断的几种方式详解

    java高并发的线程中断的几种方式详解

    这篇文章主要介绍了Java线程中断机制几种方法及示例,向大家分享了这几种方法的介绍几代码示例,具有一定参考价值,需要的朋友可以了解下。
    2021-10-10
  • SpringBoot向容器注册bean的方法详解

    SpringBoot向容器注册bean的方法详解

    这篇文章主要利用示例为大家详细介绍了SpringBoot如何向容器注册bean(即:将对象加入容器)的四种方法,文中的示例代码讲解详细,需要的可以参考一下
    2022-05-05

最新评论