springBoot配置多个数据源

27 篇文章 0 订阅

有时候项目不止只有一个数据库,可能需要有多个,根据需要切换

准备

1,新建一个springBoot项目,用idea新建很方便,不多说,pom文件的包引入

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mysql.study</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <lombok.version>1.18.6</lombok.version>
        <mybatis.version>1.3.2</mybatis.version>
        <lombox.version>1.18.6</lombox.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 添加springboot 测试坐标 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- 添加mybatis依赖坐标 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- 添加mysql驱动器坐标 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- 添加druid数据源坐标 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!-- 添加AOP坐标 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2,准备两个数据库

开始

1,配置文件:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      a-master: # 主数据源
        driverClassName: com.mysql.jdbc.Driver
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/my_test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
      b-master: # 从数据源
        driverClassName: com.mysql.jdbc.Driver
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/my_test1?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
mybatis:
  mapper-locations: classpath:mapper/*.xml

2,准备数据源配置

我们不使用默认的,要自己写个数据源配置,DynamicDataSource继承AbstractRoutingDataSource

AbstractRoutingDataSource是spring-jdbc包提供的一个了AbstractDataSource的抽象类,它实现了DataSource接口的用于获取数据库连接的方法。

AbstractRoutingDataSource的内部维护了一个名为targetDataSources的Map,并提供的setter方法用于设置数据源关键字与数据源的关系,实现类被要求实现其determineCurrentLookupKey()方法,由此方法的返回值决定具体从哪个数据源中获取连接。

package com.mysql.study.test.dataSource;

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

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

public class DynamicDataSource extends AbstractRoutingDataSource {

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

    public DynamicDataSource(DataSource defaultSource, Map<Object,Object> targetSource) {
        super.setDefaultTargetDataSource(defaultSource);
        super.setTargetDataSources(targetSource);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }

    public static void setDataSource(String dataSource) {
        contextHolder.set(dataSource);
    }

    public static String getDataSource() {
        return contextHolder.get();
    }

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

注入数据源到spring的ioc容器中去,交给spring管理,很简单,写个配置类

package com.mysql.study.test.dataSource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import org.springframework.beans.factory.annotation.Qualifier;
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 org.springframework.stereotype.Component;

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

@Component
@Configuration
public class DynamicDataSourceConfig {

    //配置数据源bean,有几个配几个
    @Bean
    @ConfigurationProperties("spring.datasource.druid.a-master")
    public DataSource aMasterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.b-master")
    public DataSource bMasterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }



    //Primary注解作用是自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常 
//这里注意方法中的入参名要跟上面的bean要一致,不然找不到,会报错,加个Qualifier注解
    @Bean
    @Primary
    public DynamicDataSource dataSource(@Qualifier("aMasterDataSource") DataSource aMasterDataSource, @Qualifier("bMasterDataSource") DataSource bMasterDataSource) {
        Map<Object,Object> map = new HashMap<>();
        map.put("a-master",aMasterDataSource);
        map.put("b-master",bMasterDataSource);
        return new DynamicDataSource(aMasterDataSource,map);

    }
}

写个注解,在mapper方法上使用就可以动态切换

package com.mysql.study.test.aspect;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    String name() default "";
}
package com.mysql.study.test.aspect;


import com.mysql.study.test.dataSource.DynamicDataSource;
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.stereotype.Component;

import javax.xml.crypto.Data;
import java.lang.reflect.Method;

@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.mysql.study.test.aspect.DataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource == null) {
            DynamicDataSource.setDataSource("a-master");
        } else {
            DynamicDataSource.setDataSource(dataSource.name());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }
}

然后我们在mapper上使用注解

package com.mysql.study.test.mapper;

import com.mysql.study.test.entity.User;
import com.mysql.study.test.aspect.DataSource;

import java.util.List;

public interface UserMapper {

    List<User> getList1();

    @DataSource( name = "b-master")
    List<User> getList();
}

第一个方法没使用注解,就默认使用主数据源,第二个使用了就会使用从数据源

启动类加下注解

package com.mysql.study.test;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.mysql.study.test.dataSource.DynamicDataSource;
import com.mysql.study.test.dataSource.DynamicDataSourceConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Import;

//取消自动加载的数据源
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
//指定扫描包
@MapperScan(basePackages = "com.mysql.study.test.mapper")
//导入自定义的配置类
@Import(DynamicDataSourceConfig.class)
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

写个controller测试下

package com.mysql.study.test.controller;

import com.mysql.study.test.entity.User;
import com.mysql.study.test.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/{name}/list")
    public List<User> list(@PathVariable("name") String name) {
        if (name.equals("master")) {
            return userMapper.getList1();
        } else {
            return userMapper.getList();
        }
    }
}

启动项目,因为这个是get方法,所以简单的用浏览器请求就行,或者用postman或者其他工具请求,根据入参的不同调用的方法不同,

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值