spring boot 多数据源集成mysql、postgresql、phoenix、doris等

如何搭建多数据源项目只要以下简单几步;

一. 创建核心在config.datasource文件夹里

二. 引入相对应的jar包

三. 创建数据库连接配置

四. 写逻辑代码进行验证

1.DataSource

java 复制代码
package com.irootech.config.datasource;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    DataSourceType value() default DataSourceType.MYSQL;
}

2.DataSourceAspect

java 复制代码
package com.irootech.config.datasource;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DataSourceAspect {

    @Before("@annotation(dataSource)")
    public void changeDataSource(DataSource dataSource) {
        DataSourceType dataSourceType = dataSource.value();
        DynamicDataSource.setDataSourceType(dataSourceType);
    }

    @After("@annotation(dataSource)")
    public void restoreDataSource(DataSource dataSource) {
        DynamicDataSource.clearDataSourceType();
    }
}

3.DataSourceConfig

java 复制代码
package com.irootech.config.datasource;


import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
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.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

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

@Configuration
@MapperScan(basePackages = "com.irootech.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {

    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "postgresDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.postgres")
    public DataSource postgresDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "phoenixDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.phoenix")
    public DataSource phoenixDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dorisDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.doris")
    public DataSource dorisDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(
            @Qualifier("mysqlDataSource") DataSource mysqlDataSource,
            @Qualifier("postgresDataSource") DataSource postgresDataSource,
            @Qualifier("phoenixDataSource") DataSource phoenixDataSource,
            @Qualifier("dorisDataSource") DataSource dorisDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MYSQL, mysqlDataSource);
        targetDataSources.put(DataSourceType.POSTGRES, postgresDataSource);
        targetDataSources.put(DataSourceType.PHOENIX, phoenixDataSource);
        targetDataSources.put(DataSourceType.DORIS, dorisDataSource);
        return new DynamicDataSource(mysqlDataSource,targetDataSources);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

4.DataSourceType

java 复制代码
package com.irootech.config.datasource;

public enum DataSourceType {
    MYSQL,
    POSTGRES,
    PHOENIX,
    DORIS
}

5.DynamicDataSource

java 复制代码
package com.irootech.config.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<DataSourceType> contextHolder = new ThreadLocal<>();

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

    @Override
    protected Object determineCurrentLookupKey() {
        return contextHolder.get();
    }

    public static void setDataSourceType(DataSourceType dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    public static DataSourceType getDataSourceType() {
        return contextHolder.get();
    }

    public static void clearDataSourceType() {
        contextHolder.remove();
    }
}
  1. DataSourceMapper
java 复制代码
package com.irootech.mapper;

import com.irootech.config.datasource.DataSource;
import com.irootech.config.datasource.DataSourceType;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface DataSourceMapper {

    @DataSource(DataSourceType.MYSQL)
    @Select("select * from data_source")
    List<Object> getDataSourceMysql();

    @DataSource(DataSourceType.PHOENIX)
    @Select("select * from data_source")
    List<Object> getDataSourcePhoenix();
}
  1. DataSourceServiceImpl
java 复制代码
package com.irootech.service.impl;

import com.irootech.mapper.DataSourceMapper;
import com.irootech.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DataSourceServiceImpl implements DataSourceService {

    @Autowired
    private DataSourceMapper dataSourceMapper;

    @Override
    public List<Object> getDataSourceMysql() {
        return dataSourceMapper.getDataSourceMysql();
    }

    @Override
    public List<Object> getDataSourcePhoenix() {
        return dataSourceMapper.getDataSourcePhoenix();
    }
}
  1. WebController
java 复制代码
package com.irootech.web;

import com.irootech.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/web_controller")
public class WebController {

    @Autowired
    private DataSourceService dataSourceService;
    @GetMapping(value ="/message")
    public String message() {
        List<Object> dataSourceMysqlList = dataSourceService.getDataSourceMysql();
        System.out.println(dataSourceMysqlList);
        List<Object> dataSourcePhoenixList = dataSourceService.getDataSourcePhoenix();
        System.out.println(dataSourcePhoenixList);
        return "WebController created";
    }
}

下载demo地址:https://download.csdn.net/download/u013772876/90233957

相关推荐
iiaythi21 分钟前
spring boot 配置文件加载顺序问题
spring boot
绝无仅有25 分钟前
GoZero 中 `make` 后返回数据与原数据不对齐的几种解决方案
后端·面试·程序员
华年源码34 分钟前
基于SpringBoot的旅游网站的设计与实现(源码+数据库+文档)
java·毕业设计·源码·springboot·旅游
程序猿零零漆39 分钟前
SpringCloud系列教程:微服务的未来(十)服务调用、注册中心原理、Nacos注册中心
java·spring cloud·微服务
编程小筑1 小时前
C语言的语法
开发语言·后端·golang
就爱学编程1 小时前
力扣刷题:数组OJ篇(上)
java·算法·leetcode
一条小小yu1 小时前
从零手写缓存框架(二)redis expire 过期原理
java·redis·缓存
XiaoH2331 小时前
培训机构Day25
java
我不是你的灯笼1 小时前
Go语言的 的输入/输出流(I/O Streams)基础知识
开发语言·后端·golang
秋の花1 小时前
【Java】List一部分常见问题
java·windows·list