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

相关推荐
hqxstudying5 分钟前
Java创建型模式---原型模式
java·开发语言·设计模式·代码规范
Dcs24 分钟前
VSCode等多款主流 IDE 爆出安全漏洞!插件“伪装认证”可执行恶意命令!
java
保持学习ing30 分钟前
day1--项目搭建and内容管理模块
java·数据库·后端·docker·虚拟机
京东云开发者41 分钟前
Java的SPI机制详解
java
超级小忍1 小时前
服务端向客户端主动推送数据的几种方法(Spring Boot 环境)
java·spring boot·后端
发仔1231 小时前
Oracle与MySQL核心差异对比
mysql·oracle
程序无bug1 小时前
Spring IoC注解式开发无敌详细(细节丰富)
java·后端
小莫分享1 小时前
Java Lombok 入门
java
程序无bug1 小时前
Spring 对于事务上的应用的详细说明
java·后端
食亨技术团队1 小时前
被忽略的 SAAS 生命线:操作日志有多重要
java·后端