栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot连接多数据源

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot连接多数据源

一、关闭自动配置
@SpringBootApplication(scanbasePackages={"com.xxxx"},exclude = {DataSourceAutoConfiguration.class})

二、在application 定义数据源配置
#一
spring.datasource.network.url=
spring.datasource.network.username=
spring.datasource.network.password=

#二
spring.datasource.sannong.url=
spring.datasource.sannong.username=
spring.datasource.sannong.password=


#三
spring.datasource.zhifa.url=
spring.datasource.zhifa.username=
spring.datasource.zhifa.password=
三、定义注解名称
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface DataSource {
    String name() default "";
}
四、定义数据库名称

注意点:这个地方的名称对应的是上面application里面配置的名称

public interface DataSourceName {
    String NETWORK = "network";
    String SAN_NONG = "sannong";
    String ZHI_FA = "zhifa";
}
五、定义配置类
@Configuration
public class DynamicDataSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.network")
    public DataSource firstDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.sannong")
    public DataSource secondDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.zhifa")
    public DataSource thirdDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource,DataSource thirdDataSource,DataSource fourthDataSource) {
        Map targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceName.NETWORK, firstDataSource);
        targetDataSources.put(DataSourceName.SAN_NONG, secondDataSource);
        targetDataSources.put(DataSourceName.ZHI_FA, thirdDataSource);
        return new DynamicDataSource(firstDataSource, targetDataSources);
    }


}
六、进行数据切换
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal contextHolder = new ThreadLocal<>();

    public DynamicDataSource(DataSource defaultTargetDataSource, Map targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        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();
    }

}
七、切面

注意点:代码里面的@Ponintcut注解内容指的是第三步的自定义注解名称DataSource

@Aspect
@Component
public class DataSourceAspect implements Ordered {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.xxx.datasource.anaotation.DataSource)")
    public void dataSourcePointCut() {
    }

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

        DataSource ds = method.getAnnotation(DataSource.class);
        if(ds == null){
            DynamicDataSource.setDataSource(DataSourceName.NETWORK);
            logger.debug("set datasource is " + DataSourceName.NETWORK);
        }else {
            DynamicDataSource.setDataSource(ds.name());
            logger.debug("set datasource is " + ds.name());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            logger.debug("clean datasource");
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
八、具体使用

在mapper层接口或者在service层接口加上@DataSource和你想要切换的名称,@DataSource就是你自定义注解的名称 

  @DataSource(name = DataSourceName.SAN_NONG)
    List queryAllVillageInfo();

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/356034.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号