SpringJPA+Druid配置多数据源

application.yml

spring:
  datasource:
    druid:
      d1:
        url: jdbc:mysql://xxx
        username: xxx
        password: xxx
        driverClassName: com.mysql.jdbc.Driver
        initial-size: 1
        max-active: 1
        min-idle: 1
        test-on-borrow: true
        validation-query: select 1
        min-evictable-idle-time-millis: 500000
        max-evictable-idle-time-millis: 600000
      d2:
        url: jdbc:mysql://xxx
        username: xxx
        password: xxx
        driverClassName: com.mysql.jdbc.Driver
        initial-size: 1
        max-active: 1
        min-idle: 1
        test-on-borrow: true
        validation-query: select 1
        connection-init-sqls: SET NAMES utf8mb4

多数据源配置

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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;

@Configuration
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.d1")
    public DataSource d1() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.d2")
    public DataSource d2() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource d1, DataSource d2) {
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put("d1", myDataSource1);
        targetDataSources.put("d2", myDataSource2);

        return new DynamicDataSource(myDataSource1, myDataSource2);
    }
}
public class DynamicDataSource extends AbstractRoutingDataSource {

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

    /**
     * 配置DataSource, defaultTargetDataSource为主数据库
     */
    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

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

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

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

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

定义注解

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DS {

    String name() default "d1";
}

定义切面

@Aspect
@Slf4j
@Configuration
public class TargetDataSourceAspect implements Ordered {

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

    @Around("@within(com.xxx.annotation.DS) " +
            "|| @annotation(com.xxx.annotation.DS)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        DS annotationInClass = AnnotationUtils.findAnnotation(point.getTarget().getClass(), DS.class);
        if (annotationInClass == null) {
            log.warn("DS annotationInClass get fail");
            return point.proceed();
        }
        String name = annotationInClass.name();
        DynamicDataSource.setDataSource(name);

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

SpringApplication记得开启AOP

使用示例:

@Service
@DS(name = "d1")
public class MyService {
	
	...省略业务代码
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于构建独立的、可执行的Spring应用程序的框架,简化了Spring应用程序的配置和部署。JPA(Java Persistence API)是一种用于管理Java对象和关系数据库之间映射的规范。Druid是阿里巴巴开源的关系型数据库连接池。 在Spring Boot中配置多数据源需要以下几步: 1. 引入相关依赖:需要引入Spring Boot、Spring Data JPADruid的相关依赖。 2. 配置数据源:在application.properties或application.yml文件中配置多个数据源的连接信息,并指定每个数据源的名称和相关属性。 3. 配置数据源连接池:使用@ConfigurationProperties注解创建多个数据源的连接池对象,并指定数据源的名称以及相关属性。 4. 配置实体管理器工厂:为每个数据源配置对应的实体管理器工厂,用于处理JPA实体与数据库之间的映射关系。 5. 配置事务管理器:为每个数据源配置对应的事务管理器,用于处理事务操作。 6. 配置数据源路由:创建动态数据源,根据传入的数据源名称选择对应的数据源进行操作。 7. 配置JPA的Repository:创建接口继承JpaRepository,用于定义数据访问方法。 通过以上步骤配置多数据源后,就可以在Spring Boot应用程序中使用多个数据源进行数据库的操作。可以根据需要在Service或Controller中使用@PersistenceContext注解指定具体的数据源,或者使用@Primary注解指定默认的数据源。 总结:通过Spring Boot的自动配置Druid的连接池,可以很方便地实现多数据源配置。使用JPA进行数据操作,能够有效地减少开发人员编写SQL语句的工作量,提高开发效率。通过合理的配置,可以根据需要选择不同的数据源进行操作,实现灵活的数据访问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值