【经验分享】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 层的方法的时候就会操作对应的数据源了

相关推荐
A阳俊yi17 分钟前
Spring Boot日志配置
java·spring boot·后端
苹果酱056717 分钟前
2020-06-23 暑期学习日更计划(机器学习入门之路(资源汇总)+概率论)
java·vue.js·spring boot·mysql·课程设计
斜月29 分钟前
一个服务预约系统该如何设计?
spring boot·后端
Lucky GGBond40 分钟前
MySQL 报错解析:SQLSyntaxErrorException caused by extra comma before FROM
数据库·mysql
echo17542542 分钟前
Apipost免费版、企业版和私有化部署详解
java
异常君1 小时前
Java 高并发编程:等值判断的隐患与如何精确控制线程状态
java·后端·代码规范
异常君1 小时前
Java 日期处理:SimpleDateFormat 线程安全问题及解决方案
java·后端·代码规范
Java水解1 小时前
Mysql之存储过程
后端·mysql
都叫我大帅哥1 小时前
Spring AI中的ChatClient:从入门到精通,一篇搞定!
java·spring·ai编程
都叫我大帅哥1 小时前
《@SpringBootApplication:Spring Boot的"一键启动"按钮,还是程序员的"免死金牌"?》
java·后端·spring