Mybatis-plus中的dynamic多数据源 配置 Mysql 和 TDengine

前言

之前不使用 mbatis-plus 下面的dynamic多数据源,对于多数据源的项目,都需要针对每个数据源写一个配置文件,很繁琐很麻烦。如下,针对Tdengine的配置。
首先在 application.yml 中配置。

在这里插入图片描述

其次创建配置类:

import com.alibaba.druid.pool.DruidDataSource;
import com.chain.common.utils.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 类名: TDengineConfig
 * 描述: TDengine配置类
 * 时间: 2022/5/13,0016 1:14
 * 开发人: wxy
 */
@Configuration
@MapperScan(basePackages = {"com.chain.iot.tdengine.dao"}, sqlSessionTemplateRef = "tdengineSqlSessionTemplate") // 声明此数据源作用的包
@ConditionalOnProperty(name = "spring.datasource.druid.tdengine-server.enabled", havingValue = "true")
public class TDengineConfig {

    @Value("${spring.datasource.druid.tdengine-server.dbName}")
    private String dbName;
    @Value("${spring.datasource.druid.tdengine-server.url}")
    private String jdbc;

    @Bean(name = "tDengineDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.tdengine-server")
    public DataSource tdengineDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "tDengineSqlSessionFactory")
    public SqlSessionFactory tDengineSqlSessionFactory(@Qualifier("tDengineDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations(StringUtils.split("classpath:mapper/tdengine/*Mapper.xml", ",")));
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }

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

    public String getDbName() {
        return dbName;
    }

    public void setDbName(String dbName) {
        this.dbName = dbName;
    }
    public Resource[] resolveMapperLocations(String[] mapperLocations)
    {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList<Resource>();
        if (mapperLocations != null)
        {
            for (String mapperLocation : mapperLocations)
            {
                try
                {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                }
                catch (IOException e)
                {
                    // ignore
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }
}

导入依赖

<!-- mp多数据源 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

<!-- TDEngine -->
<dependency>
    <groupId>com.taosdata.jdbc</groupId>
    <artifactId>taos-jdbcdriver</artifactId>
    <version>3.0.0</version>
</dependency>

<!-- Druid数据源 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.9</version>
</dependency>

配置文件 application.yml

server:
  port: 8085
  servlet:
    context-path: /lmh

# 将resources下的mapper下的xml文件都读取到 target
mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    dynamic:
      primary: master # 默认数据源
      datasource:
        master:
          url: jdbc:mysql://localhost/my_schema?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
          username: root
          password: 123456
          driver-class-name: com.mysql.cj.jdbc.Driver
        tdengine:
          url: jdbc:TAOS://master:6030/db?charset=utf-8
          driver-class-name: com.taosdata.jdbc.TSDBDriver
          username: root
          password: taosdata
    druid:
      initialSize: 5
      minIdle: 5
      maxActive: 200
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: false
      filters: stat,wall,log4j2
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Mapper接口与xml编写

在这里插入图片描述

TdengineInfoMapper.xml :

在这里插入图片描述

测试查询

在这里插入图片描述
运行结果:
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
mybatis-plus-dynamic-datasource 获取多数据源实例的方法如下: 1. 导入相关依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>2.5.3</version> </dependency> ``` 2. 在 application.yml 或 application.properties 配置数据源信息,例如: ```yaml spring: datasource: dynamic: primary: ds1 # 设置默认数据源 datasource: ds1: url: jdbc:mysql://localhost:3306/db1 username: root password: 123456 ds2: url: jdbc:mysql://localhost:3306/db2 username: root password: 123456 ``` 3. 创建一个继承自 AbstractRoutingDataSource 的类,用于动态切换数据源: ```java public class DynamicRoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DynamicDataSourceContextHolder.getDataSourceKey(); } } ``` 4. 创建一个数据源上下文持有者类,用于设置和获取当前线程使用的数据源: ```java public class DynamicDataSourceContextHolder { private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>(); public static void setDataSourceKey(String dataSourceKey) { CONTEXT_HOLDER.set(dataSourceKey); } public static String getDataSourceKey() { return CONTEXT_HOLDER.get(); } public static void clearDataSourceKey() { CONTEXT_HOLDER.remove(); } } ``` 5. 配置数据源切换策略和数据源 bean: ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.dynamic") public DataSourceProperties dataSourceProperties() { return new DataSourceProperties(); } @Bean public DataSource dataSource(DataSourceProperties properties) { Map<String, DataSource> dataSourceMap = new HashMap<>(); dataSourceMap.put("ds1", properties.getDataSource("ds1")); dataSourceMap.put("ds2", properties.getDataSource("ds2")); // 设置默认数据源 DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(); dataSource.setDefaultTargetDataSource(dataSourceMap.get(properties.getPrimary())); dataSource.setTargetDataSources(dataSourceMap); return dataSource; } @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource); return sessionFactoryBean.getObject(); } @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } ``` 现在,你可以通过注入 DataSource 类型的 bean 来获取多数据源实例,例如: ```java @Autowired private DataSource dataSource; ``` 然后,你就可以使用这个数据源实例来执行数据库操作了。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

henulmh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值