【经验分享】SpringCloud + MyBatis Plus 配置 MySQL,TDengine 双数据源

概述

因为项目中采集工厂中的设备码点的数据量比较大,需要集成TDengine时序数据库,所以需要设置双数据源

操作步骤

导入依赖

XML 复制代码
		<!-- 多数据源支持 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.3.6</version>
        </dependency>
		<!-- taos连接驱动 -->
        <dependency>
            <groupId>com.taosdata.jdbc</groupId>
            <artifactId>taos-jdbcdriver</artifactId>
            <version>3.2.11</version>
        </dependency>

nacos 配置文件数据源修改

XML 复制代码
spring:
    servlet:
        multipart:
            max-file-size: 100MB
            max-request-size: 100MB
            enabled: true
    # mysql 配置
    datasource:
        dynamic:
            primary: mysql-server
        type: com.alibaba.druid.pool.DruidDataSource
        mysql-server:
            driver-class-name: com.mysql.cj.jdbc.Driver
            jdbc-url: jdbc:mysql://ip:port/db?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
            username: username
            password: password
            initial-size: 10
            max-active: 100
            min-idle: 10
            max-wait: 60000
            pool-prepared-statements: true
            max-pool-prepared-statement-per-connection-size: 20
            time-between-eviction-runs-millis: 60000
            min-evictable-idle-time-millis: 300000
            test-while-idle: true
            test-on-borrow: false
            test-on-return: false
            stat-view-servlet:
                enabled: true
                url-pattern: /druid/*
            filter:
                stat:
                    log-slow-sql: true
                    slow-sql-millis: 1000
                    merge-sql: false
                wall:
                    config:
                        multi-statement-allow: true
		# TDengine 配置
        tdengine-server:
            driver-class-name: com.taosdata.jdbc.rs.RestfulDriver
            jdbc-url: jdbc:TAOS-RS://ip:port/db?timezone=UTC-8&charset=utf-8
            username: username
            password: password
            pool-name: Data_trans_HikariCP
            minimum-idle: 10 #最小空闲连接数量
            idle-timeout: 600000 #空闲连接存活最大时间,默认600000(10分钟)
            maximum-pool-size: 100 #连接池最大连接数,默认是10
            auto-commit: true  #此属性控制从池返回的连接的默认自动提交行为,默认值:true
            max-lifetime: 1800000 #此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
            connection-timeout: 30000 #数据库连接超时时间,默认30秒,即30000

新增自定义数据源配置类

MySQL

java 复制代码
/**
 * MySQL 双数据源配置
 * @author pumpkin
 * @date 2024/5/16 14:08
 */
@Configuration
@MapperScan(basePackages = {"com.xxx.xxx.xxx.dao", "com.xxx.xxx.xxx.dao"}, sqlSessionTemplateRef  = "mysqlSqlSessionTemplate")
public class MysqlServerConfig {

    private final MybatisPlusProperties properties;

    public MysqlServerConfig(MybatisPlusProperties properties) {
        this.properties = properties;
    }

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

    @Bean(name = "mysqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
//        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        // 指定多个XML映射文件位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//        bean.setMapperLocations(resolver.getResources("classpath*:/mapper/*.xml"));

        Resource[] resources1 = resolver.getResources("classpath*:mapper/**/*.xml");
        Resource[] resources2 = resolver.getResources("classpath*:mapper/*.xml");
        // 将多个资源数组合并为一个
        Resource[] mapperLocations = new Resource[resources1.length + resources2.length];
        System.arraycopy(resources1, 0, mapperLocations, 0, resources1.length);
        System.arraycopy(resources2, 0, mapperLocations, resources1.length, resources2.length);
        // 设置合并后的资源数组
        bean.setMapperLocations(mapperLocations);

//        MybatisConfiguration configuration = this.properties.getConfiguration();
//        if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
//            configuration = new MybatisConfiguration();
//        }
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setDefaultFetchSize(100);
        configuration.setDefaultStatementTimeout(30);
        bean.setConfiguration(configuration);

        return bean.getObject();
    }

    @Bean(name = "mysqlTransactionManager")
    @Primary
    public DataSourceTransactionManager mysqlTransactionManager(@Qualifier("mysqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mysqlSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

TDengine

java 复制代码
/**
 * TDengine 双数据源配置
 * @author pumpkin
 * @date 2024/5/16 14:08
 */
@Configuration
@MapperScan(basePackages = {"com.xxx.xxx.xxx.tdengine"}, sqlSessionTemplateRef  = "tdengineSqlSessionTemplate")
public class TDengineServerConfig {

    @Bean(name = "tdengineDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.tdengine-server")
    public DataSource tdengineDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "tdengineSqlSessionFactory")
    public SqlSessionFactory tdengineSqlSessionFactory(@Qualifier("tdengineDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/tdengine/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "tdengineTransactionManager")
    public DataSourceTransactionManager tdengineTransactionManager(@Qualifier("tdengineDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "tdengineSqlSessionTemplate")
    public SqlSessionTemplate tdengineSqlSessionTemplate(@Qualifier("tdengineSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

将访问对应数据源的 Mapper 类放在对应的包下,使用 DAO 或者 Mapper 层的方法的时候就会操作对应的数据源了

相关推荐
hay_lee2 小时前
Spring AI实现对话聊天-流式输出
java·人工智能·ollama·spring ai
Exquisite.2 小时前
Mysql
数据库·mysql
Hx_Ma162 小时前
SpringBoot数据源自动管理
java·spring boot·spring
SunnyDays10112 小时前
Java 高效实现 CSV 转 Excel
java·csv转excel
starfire_hit2 小时前
JAVAWEB根据前台请求获取用户IP
java·服务器·网络
fengxin_rou2 小时前
[Redis从零到精通|第四篇]:缓存穿透、雪崩、击穿
java·redis·缓存·mybatis·idea·多线程
像少年啦飞驰点、2 小时前
从零开始学 RabbitMQ:小白也能懂的消息队列实战指南
java·spring boot·微服务·消息队列·rabbitmq·异步编程
宠友信息2 小时前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
AI职业加油站2 小时前
职业提升之路:我的大数据分析师学习与备考分享
大数据·人工智能·经验分享·学习·职场和发展·数据分析
java1234_小锋2 小时前
Java高频面试题:Spring和SpringBoot的关系和区别?
java·spring boot·spring