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

相关推荐
码界奇点1 天前
基于Spring Boot的内容管理系统框架设计与实现
java·spring boot·后端·车载系统·毕业设计·源代码管理
墨雪不会编程1 天前
C++【string篇1遍历方式】:从零开始到熟悉使用string类
java·开发语言·c++
蒂法就是我1 天前
有一张表,只有一个字段没有插入主建,能插入成功吗? 隐藏的 rowid除了在这里用到还在哪里用到了?
java
a努力。1 天前
字节Java面试被问:系统限流的实现方式
java·开发语言·后端·面试·职场和发展·golang
独自破碎E1 天前
Java中的Exception和Error有什么区别?
java·开发语言
小徐Chao努力1 天前
【Langchain4j-Java AI开发】08-向量嵌入与向量数据库
java·数据库·人工智能
qq_377112371 天前
从零开始深入理解并发、线程与等待通知机制
java·开发语言
小徐Chao努力1 天前
【Langchain4j-Java AI开发】07-RAG 检索增强生成
java·人工智能·python
JoannaJuanCV1 天前
自动驾驶—CARLA仿真(30)交通管理器(Traffic Manager)
java·redis·自动驾驶
小高Baby@1 天前
使用Go语言中的Channel实现并发编程
开发语言·后端·golang