spring-boot使用AOP实现读写分离

spring-boot使用AOP实现读写分离

一、自定义数据源

在配置文件中定义数据源

spring:
  datasource:
    master:
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://centosA:3306/baizhi?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC&useSSL=false
    slave1:
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://centosB:3306/baizhi?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC&useSSL=false
    slave2:
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://centosC:3306/baizhi?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC&useSSL=false

读取配置文件中的数据源

package com.baizhi.datasource;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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 org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

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

@Configuration
public class UserDefineDatasourceConfig {
   
    @Bean
    //读取前缀为spring.datasource.master的配置创建数据源并交给工厂,类名为方法名
    @ConfigurationProperties("spring.datasource.master")
    public DataSource masterDataSource() {
   
        return DataSourceBuilder.create().build();
    }

    @Bean
    //读取前缀为spring.datasource.slave1的配置创建数据源并交给工厂,类名为方法名
    @ConfigurationProperties("spring.datasource.slave1")
    public DataSource slave1DataSource() {
   
        return DataSourceBuilder.create<

你可能感兴趣的:(mybatis,AOP,spring,mybatis,aop,mysql)