springBoot + druid +mysql 实现读写分离

1、首先配置yml配置文件:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    master:
      url: jdbc:mysql://192.168.145.145:3306/gourd?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: root
    slave:
      url: jdbc:mysql://192.168.145.146:3306/gourd?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: root
    druid:
      initial-size: 5
      max-wait: 60000
      min-idle: 1
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: select 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-open-prepared-statements: 50
      max-pool-prepared-statement-per-connection-size: 20
  

如果只有一个数据库,master和slave配置成一样即可;
如果有两个数据库,数据库需配置主从复制,参考:https://blog.csdn.net/HXNLYW/article/details/90373149

数据库密码加密:https://blog.csdn.net/HXNLYW/article/details/98635913

druid依赖包:

<!--Druid连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>

2、定义主从数据库名

import lombok.Data;

/**
 * @author gourd
 */
@Data
public class CommonConstant {

    /**
     * 主数据源
     */
    public static final String MASTER_DATASOURCE = "masterDruidDataSource";

    /**
     * 从数据源
     */
    public static final String SLAVE_DATASOURCE= "slaveDruidDataSource";
}

3、定义目标数据库注解及AOP切面

import com.gourd.common.constant.CommonConstant;
import java.lang.annotation.*;

/**
 * @program: springboot
 * @description: 动态切换数据源注解
 * @author: gourd
 * @date: 2018-11-22 14:02
 * @since: 1.0
 **/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TargetDataSource {
    String value() default CommonConstant.MASTER_DATASOURCE;
//    //代码切换到数据源
//    DynamicDataSource.setDataSource(CommonConstant.MASTER_DATASOURCE);
//    DynamicDataSource.clearDataSource();
}
import com.gourd.base.annotation.TargetDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
 
import java.lang.reflect.Method;
 
/**
 * @program: springboot
 * @description: 动态切换数据源AOP切面处理
 * @author: gourd
 * @date: 2018-11-22 14:03
 * @since: 1.0
 **/
@Aspect
@Component
@Slf4j
public class DataSourceAspect implements Ordered {

    /**
     * 切点: 所有配置 TargetDataSource 注解的方法
     */
    @Pointcut("@annotation(com.gourd.base.annotation.TargetDataSource)")
    public void dataSourcePointCut() {}
 
    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        TargetDataSource ds = method.getAnnotation(TargetDataSource.class);
        // 通过判断 @ChangeDataSource注解 中的值来判断当前方法应用哪个数据源
        DynamicDataSource.setDataSource(ds.value());
        log.info("^o^= 当前数据源: " + ds.value());
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            log.debug("^o^= clean datasource");
        }
    }
    @Override
    public int getOrder() {
        return 1;
    }
}

4、动态数据源创建:

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 
import javax.sql.DataSource;
import java.util.Map;
 
/**
 * @program: springboot
 * @description: 创建动态数据源
 * 实现数据源切换的功能就是自定义一个类扩展AbstractRoutingDataSource抽象类,
 * 其实该相当于数据源DataSourcer的路由中介,
 * 可以实现在项目运行时根据相应key值切换到对应的数据源DataSource上。
 * @author: gourd
 * @date: 2018-11-22 13:59
 * @since: 1.0
 **/
public class DynamicDataSource extends AbstractRoutingDataSource {
 
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
 
    /**
     * 配置DataSource, defaultTargetDataSource为主数据库
     */
    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        //设置默认数据源
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        //设置数据源列表
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }
 
    /**
     * 是实现数据源切换要扩展的方法,
     * 该方法的返回值就是项目中所要用的DataSource的key值,
     * 拿到该key后就可以在resolvedDataSource中取出对应的DataSource,
     * 如果key找不到对应的DataSource就使用默认的数据源。
     * */
    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }
 
    /**
     * 绑定当前线程数据源路由的key
     * 使用完成后必须调用removeRouteKey()方法删除
     */
    public static void setDataSource(String dataSource) {
        contextHolder.set(dataSource);
    }
 
    /**
     * 获取当前线程的数据源路由的key
     */
    public static String getDataSource() {
        return contextHolder.get();
    }
 
    /**
     * 删除与当前线程绑定的数据源路由的key
     */
    public static void clearDataSource() {
        contextHolder.remove();
    }
 
}

5、动态数据源配置类:

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.gourd.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springboot
 * @description: 动态数据源配置
 * @author: gourd
 * @date: 2018-11-22 14:01
 * @since: 1.0
 **/
@Configuration
@Slf4j
public class DynamicDataSourceConfig {



    /**
     * 创建 TargetDataSource Bean
     */
    @Bean
    @ConfigurationProperties("spring.datasource.master")
    public DataSource masterDataSource() {
        DataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }

    @Bean
    @ConfigurationProperties("spring.datasource.slave")
    public DataSource slaveDataSource() {
        DataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }

    /**
     * 如果还有数据源,在这继续添加 TargetDataSource Bean
     */

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(CommonConstant.MASTER_DATASOURCE, masterDataSource);
        targetDataSources.put(CommonConstant.SLAVE_DATASOURCE, slaveDataSource);
        // 还有数据源,在targetDataSources中继续添加
        log.info("^o^= DataSources:" + targetDataSources);
        //默认的数据源是oneDataSource
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }

}

6、以上就已经配置完成了读写分离,下面是用法:

1)方法上加注解

    @Override
    @TargetDataSource(DataSourceNames.SLAVE_DATASOURCE)
    public ResponseUserToken login(String username, String password) {
    }

2)代码中切换数据源,默认主数据源:

    //代码切换到数据源
    DynamicDataSource.setDataSource(DataSourceNames.SLAVE_DATASOURCE);
   

有兴趣的小伙伴可以下载源码项目:https://blog.csdn.net/HXNLYW/article/details/98037354

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
实现读写分离可以利用 SpringBoot、MybatisPlus 和 Druid 进行配置。下面是一个简单的实现过程: 1. 添加 MybatisPlus 和 Druid 的 Maven 依赖。 ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 2. 在配置文件中添加 Druid 数据源相关配置。 ```yaml spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource druid: initialSize: 5 maxActive: 10 minIdle: 5 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 filters: stat,wall,log4j connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 3. 配置 MybatisPlus 的多数据源功能。 ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceType.MASTER.getType(), masterDataSource); targetDataSources.put(DataSourceType.SLAVE.getType(), slaveDataSource); return new DynamicDataSource(masterDataSource, targetDataSources); } } ``` 4. 创建一个 DataSourceHolder 类,用于保存当前线程的数据源类型。 ```java public class DataSourceHolder { private static final ThreadLocal<String> HOLDER = new ThreadLocal<>(); public static String getDataSource() { return HOLDER.get(); } public static void setDataSource(String dataSource) { HOLDER.set(dataSource); } public static void clearDataSource() { HOLDER.remove(); } } ``` 5. 创建一个枚举类型 DataSourceType,用于表示数据源类型。 ```java public enum DataSourceType { MASTER("master"), SLAVE("slave"); private final String type; DataSourceType(String type) { this.type = type; } public String getType() { return type; } } ``` 6. 创建一个 DynamicDataSource 类,继承 AbstractRoutingDataSource,用于动态切换数据源。 ```java public class DynamicDataSource extends AbstractRoutingDataSource { private final Map<Object, Object> targetDataSources; public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) { super.setDefaultTargetDataSource(defaultDataSource); this.targetDataSources = targetDataSources; super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } @Override protected Object determineCurrentLookupKey() { return DataSourceHolder.getDataSource(); } @Override public void setTargetDataSources(Map<Object, Object> targetDataSources) { this.targetDataSources.putAll(targetDataSources); super.setTargetDataSources(this.targetDataSources); super.afterPropertiesSet(); } @Override public void addTargetDataSource(Object key, Object dataSource) { this.targetDataSources.put(key, dataSource); super.setTargetDataSources(this.targetDataSources); super.afterPropertiesSet(); } } ``` 7. 创建一个 AopDataSourceConfig 类,用于配置切面,实现动态切换数据源。 ```java @Configuration public class AopDataSourceConfig { @Bean public DataSourceAspect dataSourceAspect() { return new DataSourceAspect(); } } ``` ```java @Aspect public class DataSourceAspect { @Pointcut("@annotation(com.example.demo.annotation.Master) " + "|| execution(* com.example.demo.service..*.select*(..)) " + "|| execution(* com.example.demo.service..*.get*(..)) " + "|| execution(* com.example.demo.service..*.query*(..)) " + "|| execution(* com.example.demo.service..*.find*(..)) " + "|| execution(* com.example.demo.service..*.count*(..))") public void read() { } @Pointcut("execution(* com.example.demo.service..*.insert*(..)) " + "|| execution(* com.example.demo.service..*.update*(..)) " + "|| execution(* com.example.demo.service..*.delete*(..))") public void write() { } @Around("read()") public Object read(ProceedingJoinPoint joinPoint) throws Throwable { try { DataSourceHolder.setDataSource(DataSourceType.SLAVE.getType()); return joinPoint.proceed(); } finally { DataSourceHolder.clearDataSource(); } } @Around("write()") public Object write(ProceedingJoinPoint joinPoint) throws Throwable { try { DataSourceHolder.setDataSource(DataSourceType.MASTER.getType()); return joinPoint.proceed(); } finally { DataSourceHolder.clearDataSource(); } } } ``` 8. 在 Service 层的方法上使用 @Master 注解,表示强制使用主库。 ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override @Master public boolean save(User user) { return super.save(user); } } ``` 这样就实现读写分离功能。需要注意的是,在使用 MybatisPlus 进行 CRUD 操作时,需要使用对应的 Service 方法,例如 selectList、selectPage、insert、updateById、deleteById,而不是直接调用 Mapper 方法。否则,数据源切换将不会生效。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值