springboot整合mybatis-plus、clickhouse、mysql多数据源

2023-05-16

springboot的多数据源有多种方式,本文按照指定不同dao/mapper.xml的方式来实现访问不同的数据源。这样的好处是不用注解去切换数据源。

1、引入驱动

<dependency>
   <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>${druid.version}</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatisplus.boot.version}</version>
</dependency>

<!-- mysql -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
</dependency>
<!-- clickhouse-->
<dependency>
    <scope>compile</scope>
    <groupId>com.clickhouse</groupId>
    <artifactId>clickhouse-jdbc</artifactId>
    <version>${clickhouse-jdbc.version}</version>
</dependency>
<!-- 分页pagehelper-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>${pagehelper.version}/version>
    <scope>compile</scope>
</dependency>

2、配置连接信息

spring:
  datasource:
    first:
      url: jdbc:mysql://192.168.11.89:3308/watch_platform?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
      username: root
      password: zdxf123
      type: com.alibaba.druid.pool.DruidDataSource
      driverClassName: com.mysql.cj.jdbc.Driver
    ch:
      url: jdbc:clickhouse://192.168.11.89:8123/watch_platform
      username: default
      password: zdxf@2022
      type: com.alibaba.druid.pool.DruidDataSource
      driverClassName: com.clickhouse.jdbc.ClickHouseDriver
    #druid配置
    druid:
      validation-query: SELECT 1
      initial-size: 10 # 初始化连接:连接池启动时创建的初始化连接数量
      max-active: 1000 # 最大活动连接:连接池在同一时间能够分配的最大活动连接的数量,如果设置为非正数则表示不限制
      min-idle: 10 # 最小空闲连接:连接池中容许保持空闲状态的最小连接数量,低于这个数量将创建新的连接,如果设置为0则不创建
      max-wait: 60000 # 最大等待时间:当没有可用连接时,连接池等待连接被归还的最大时间(以毫秒计数),超过时间则抛出异常,如果设置为-1表示无限等待
      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/*
     login-username: druid # sql-stat监控用户名
       login-password: 123456 # sql-stat监控密码
     filter:
       stat:
         log-slow-sql: true
         slow-sql-millis: 1000
         merge-sql: false
       wall:
         config:
           multi-statement-allow: true

3、配置文件

mysql配置文件MysqlConf :


import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.incrementer.OracleKeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

/**
 * mysql数据源配置
 * @author lanbo
 *
 */

@Configuration
@MapperScan(basePackages = "com.xxxx.modules.*.dao", sqlSessionFactoryRef = "firstSqlSessionFactory")
public class MysqlConf {

    @Primary
    @Bean(name = "firstDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.first")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Primary
    @Bean(name = "firstSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource,@Qualifier("mybatisConfiguration")MybatisConfiguration mybatisConfiguration,@Qualifier("globalConfig")GlobalConfig globalConfig) throws Exception {
    	MybatisSqlSessionFactoryBean  factoryBean = new MybatisSqlSessionFactoryBean();
        mybatisConfiguration.addInterceptor(new PaginationInterceptor());
        factoryBean.setConfiguration(mybatisConfiguration);
        GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
        dbConfig.setKeyGenerator(new OracleKeyGenerator());
        factoryBean.setGlobalConfig(globalConfig);
        factoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/**/*Dao.xml"));
        return factoryBean.getObject();
    }

    @Primary
    @Bean(name = "firstTransactionManager")
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

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

}

配置文件MybatisConfig :



import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 插件配置
 *
 * @author zj
 */
@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor pageClick = new PaginationInnerInterceptor(DbType.CLICK_HOUSE);
        PaginationInnerInterceptor pageMysql = new PaginationInnerInterceptor(DbType.MYSQL);
        mybatisPlusInterceptor.addInnerInterceptor(pageClick);
        mybatisPlusInterceptor.addInnerInterceptor(pageMysql);
        return mybatisPlusInterceptor;
    }
}

clickhouse的配置文件ChConfig:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Author LeeShaw
 * @Description 连接配置信息
 * @Date 2022/3/31 16:47
 **/
@ConfigurationProperties(prefix = "spring.datasource.ch")
@Data
@Component
public class ChConfig {
    private String url;
    private String username;
    private String password;
    private String type;
    private String driverClassName;

}

clickhouse的配置文件ClickHouseConfig:


import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Author LeeShaw
 * @Description
 * @Date 2022/3/31 9:45
 **/
@Configuration
@MapperScan(basePackages = "com.xxxx.clickhouse.dao", sqlSessionFactoryRef = "clickhouseSqlSessionFactory")
public class ClickHouseConfig {
    @Autowired
    private ChConfig config;

    @Bean(name = "clickhouseDataSource")
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(config.getUrl());
        druidDataSource.setUsername(config.getUsername());
        druidDataSource.setPassword(config.getPassword());
        druidDataSource.setDbType(config.getType());
        druidDataSource.setDriverClassName(config.getDriverClassName());
        return druidDataSource;
    }

    @Bean(name = "clickhouseSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("clickhouseDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.addInterceptor(new PaginationInterceptor());
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setLogImpl(StdOutImpl.class);
        factoryBean.setConfiguration(configuration);
        factoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        PageInterceptor pageHelper = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "false");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        factoryBean.setPlugins(new Interceptor[] { pageHelper });
        factoryBean.setMapperLocations(resolver.getResources("classpath*:clickhouse/*Dao.xml"));
        return factoryBean.getObject();
    }

    @Bean(name = "clickhouseTransactionManager")
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("clickhouseDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "clickhouseSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("clickhouseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

4、目录结构

mysql的dao/mapper文件放在常规的目录下;clickhouse在单独目录下,如果想修改,在ClickHouseConfig里修改 @MapperScan(basePackages = "com.xxxx.yyyy.dao", sqlSessionFactoryRef = "clickhouseSqlSessionFactory")和 factoryBean.setMapperLocations(resolver.getResources("classpath*:clickhouse/*Dao.xml"));
在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot整合mybatis-plus、clickhouse、mysql多数据源 的相关文章

  • PX4飞控试炼之路

    PX4飞控试炼之路 一 地面站控制台上显示输出 Hello Sky 二 利用飞控计算加法三 飞控按指定频率计数 xff0c 并将计数结果反馈到控制台1 利用while循环实现计数2 利用 96 hrt call every 96 周期回调函
  • 解决电脑wlan被禁用无法再启动的办法.

    快捷键ctrl 43 alt 43 delete打开任务管理器 gt 选择服务 gt 左下角打开服务 gt 找到WLAN AutoConfig右键 gt 选择重新启动 xff0c 然后Ok了
  • 关于虚拟机ubuntu编译程序时报make: warning: Clock skew detected. Your build may be incomplete.问题的解决办法

    关于ubuntu虚拟机编译程序时报make warning Clock skew detected Your build may be incomplete 问题的解决办法 xff1a 我在ubuntu虚拟的arm linux gcc上编译
  • 解决rosbag时间戳未对齐的解决方法

    解决rosbag时间戳未对齐的解决方法 Reference ROS org rosbag Cookbook http wiki ros org rosbag Cookbook rosbag在存储时间时 xff0c 接收消息的时间和生成消息的
  • ROS+python控制小乌龟走方形的实现rospy

    常见的简陋的控制乌龟行走方形的方式很简单 xff0c 例如 xff1a 代码有些地方是测试用的 xff0c 可以不要 usr bin env python from pickle import TRUE import rospy from
  • C++ STL算法

    C 43 43 STL算法 1 非修正序列算法1 1 adjacent find first last 1 2 count first last val 2 修正序列算法2 1 random shuffle first last 2 2 p
  • git子模块的修改和更新操作

    Reference git子模块的修改和更新操作 1 子库与父库 git关于子模块的官方文档链接 xff1a https git scm com book zh v2 Git E5 B7 A5 E5 85 B7 E5 AD 90 E6 A8
  • CMakeLists Option使用简介

    CMakeLists Option使用简介 1 基本格式2 示例3 基本用法4 C程序条件编译5 次项目之间选项的关系 Reference xff1a CMake之Option使用简介 CMake中的option用于控制编译流程 xff0c
  • 四轴一键起飞定高定点悬停伪代码

    四轴飞行器一键起飞定高 xff0c 降落 xff0c 光流定点悬停控制算法伪代码 基于飞控系统的二次开发
  • 开源飞控地面站 Openpilot GCS (现在的Librepilot GCS)源码分析  (2)地图插件

    xff08 xff11 xff09 OpenPilot项目中有地图显示模块 xff08 xff12 xff09 地图显示模块的插件是 xff1a opmap插件 xff0c 位置是src gt plugins gt opmap xff08
  • ubuntu 下运行程序报错 对‘std::cout’未定义的引用:gcc与g++的区别

    目录 1 问题提出 2 gcc与g 43 43 的区别 2 1 预处理 2 2 编译 2 3 汇编 2 4 链接运行 3 总结 1 问题提出 linux初学 xff0c 写了个例程 xff0c 用gcc o编译时出现以下问题 xff1a 后
  • 2.2 开启调度器

    开启调度器 void vTaskStartScheduler void BaseType t xReturn if configSUPPORT STATIC ALLOCATION 61 61 1 静态创建空闲任务 StaticTask t
  • 4. 消息队列

    消息队列 队列又称消息队列 xff0c 常用于任务间通信的数据结构 xff0c 可以在任务与任务之间 xff0c 中断与任务之间传递消息 xff0c 实现任务接收来自其他任务或中断的不固定长度的消息 任务可从消息队列中读取消消息 xff0c
  • 网卡接口

    网络接口 网络接口 xff08 以太网 xff09 是硬件接口 xff0c LwIP是软件 xff0c 并且网卡也是由很多种的 LwIP使用一个数据结构 xff0c nitif来描述网卡 用户提供最底层的接口函数 xff0c LwIP则提供
  • 系统扇区

    系统结构 DBR xff0c 主引导记录 xff1b DPT xff0c 分区表 xff1b DBR xff0c 分区引导扇区 引导扇区 MBR Main Boot Record xff0c 主引导扇区 xff0c 硬盘主引导记录区 xff
  • 华为3COM交换机配置命令详解

    1 配置文件相关命令 Quidway display current configuration 显示当前生效的配置 Quidway display saved configuration xff1b 显示flash中配置文件 xff0c
  • 分区结构

    分区结构 DBR xff0c 引导记录区 xff0c 包括一个引导程序和一个BPB xff0c 即本分区参数记录表 系统可直接访问的第一个扇区 xff0c 大小为512个字节 xff08 特殊情况占用其他保留扇区 xff09 512字节中
  • 1. 列表和列表项

    列表和列表项 列表 列表是一个数据结构 xff0c 用来追踪任务 xff0c 列表中有一个指针指向列表项 列表是一个结构体 xff0c 内部携带一个指针 xff0c 指针指向列表项 xff0c 列表项形成双向链式结构挂载在列表下 一个列表下
  • C#简单串口调试助手【傻瓜教程】chanson_chapter01

    简易串口调试助手制作教程 C Winform chanson chapter01 说明 xff1a 本教程基于win10 x64 位操作系统 xff0c 软件环境为Microsoft Visual Studio Community 2015
  • 快速上手Ubuntu之安装篇——安装win7,Ubuntu16.04双系统

    Linux可以说是开发者的系统 xff0c 对于开发者来说 xff0c Linux发行版不仅为我们提供了无数强大的开发工具 xff0c 还能帮助我们从源码上学习操作系统是工作的 而且经常在命令行上工作的我们还能在别人面前耍下酷 Ubuntu

随机推荐

  • SpringBoot中事件的使用

    项目中很多场景可以使用事件来对系统进行解耦 xff0c 让系统更便于维护和扩展 SpringBoot项目默认是支持事件的 xff0c 我们只需要自定义事件 xff0c 然后发布事件 xff0c 之后监听事件处理业务逻辑即可 SpringBo
  • STM32F4串口通信(UART)详解

    UART串口通信 我们在生活中处处都会接触到或者是用到通信 QQ 微信 电话 这些都是最常见的人与人之间远程无线通信的方式 那么也有像红外遥控 蓝牙数据传输等器件或硬件之间的通信 这些通信方式都有一些共同点 无线 易受干扰 信号变差 等 而
  • 高度自定义的简繁转换 VS2022 C++ 工程

    首先秀一下简繁转换结果图 如下 include lt iostream gt include 34 KOpenCC KOpenCCExport h 34 include lt string gt ifdef WIN64 pragma com
  • 关于 make_unique 和 make_shared

    C 43 43 14 才加入make unique xff0c 据说当时忘记实现了 那么C 43 43 11 可以自己实现这个功能 xff1a template lt typename T typename Args gt std uniq
  • 音视频OSD——修改叠加信息的尺寸

    目录 分析 原理 错误想法 思考 代码 c h 效果 分析 在实际场景中 可能出现字模尺寸使用不合理的情况 此时就需要对OSD叠加的信息进行相应的缩放 思路如下 放大 位图中每个点 在YUV图像中画四个点 即放大两倍 缩小 位图中取奇数行或
  • ABAP 常用的系统变量說明

    系统内部有一个专门存放系统变量的结构SYST 其中最常用的系统变量有 SY SUBRC 系统执行某指令后 表示执行成功与否的变量 0 表示成功 SY UNAME 当前使用者登入SAP的USERNAME SY DATUM 当前系统日期 SY
  • 第四次产业革命源于人工智能(趋势…

    第四次产业革命源于人工智能 xff08 趋势解读 20 k字 xff09 秦陇纪10汇编 第四次产业革命源于人工智能 xff08 趋势解读 20 k字 xff09 xff0c 附 数据简化DataSimp 技术描述 学会及社区1k字 欢迎关
  • 无人机开源吊舱+云台+AI芯片级解决方案 (回复“无人机AI方案”下载PDF资料)

    无人机开源吊舱 43 云台 43 AI芯片级解决方案 xff08 回复 无人机AI方案 下载PDF资料 xff09 原创 xff1a 云汉智能 科学Sciences 今天 科学 Sciences 导读 xff1a 无人机开源吊舱 43 云台
  • Ubuntu16.04 远程桌面连接(VNC)

    1 查看我的Ubuntu系统版本 2 客户机win10下载vnc viewer安装 xff1a 下载地址 xff1a https download csdn net download qq 28284093 10387251 点击打开链接
  • Mark一下YOLO检测和跟踪

    主要在看这个 YOLO算法的原理与实现 https blog csdn net xiaohu2022 article details 79211732 E7 AE 97 E6 B3 95 E7 9A 84tf E5 AE 9E E7 8E
  • ROS中的launch文件

    launch文件怎么写 首先 xff0c ROS中的launch文件是自己创建的 xff08 我在ROS包源文件中并没有发现 xff09 接下来是launch文件的编写 xff0c 需要注意 1 xff1a 开头是 lt launch gt
  • Git Submodule管理项目子模块

    使用场景 当项目越来越庞大之后 xff0c 不可避免的要拆分成多个子模块 xff0c 我们希望各个子模块有独立的版本管理 xff0c 并且由专门的人去维护 xff0c 这时候我们就要用到git的submodule功能 常用命令 git cl
  • Spring Boot结合easyExcel实现自增序号

    有些业务功能要求能导出序号 xff0c 现在提供两种实现方式 通过mysql查询实现 xff1b 实现RowWriteHandler接口 xff0c 自定义拦截器 xff1b 一 通过mysql查询实现 通过自定义变量实现每行数据 43 1
  • Spring Boot 实体里的List集合参数验证

    Spring Boot 实体里的List集合参数验证 Spring Boot 通过Hibernate Validator 加验证大家都知道 不知道的话可以参考这篇文章SpringBoot里参数校验 参数验证 今天讲一下Spring Boot
  • 树形结构工具类,如:菜单、部门等

    1 树节点 span class token keyword package span span class token namespace com span class token punctuation span zjson span
  • EasyPoiUtil导出工具

    span class token keyword package span span class token namespace com span class token punctuation span zjson span class
  • sap上传excel文档字符限制处理

    abap中有多个函数处理上传的excel文档中的数据 xff0c 记录数据的信息 xff08 行 列 值 xff09 如 xff0c 函数KCD EXCEL OLE TO INT CONVERT xff1a data lt data in
  • ffmpeg部署和springboot使用

    视频存储部署 一 环境安装 1 1 yasm安装 在编译ffmpeg时 xff0c 执行 configure xff0c 报出了如下错误 xff1a nasm yasm not found or too old Use disable x8
  • 【docker】安装clickhouse

    一 联网安装clickhouse 1 为了方便安装 xff0c 将clickhouse的工作目录和数据目录都在同一个目录下 xff0c 在home下创建目录 mkdir clickhouse cd clickhouse 创建日志 配置文件
  • springboot整合mybatis-plus、clickhouse、mysql多数据源

    springboot的多数据源有多种方式 xff0c 本文按照指定不同dao mapper xml的方式来实现访问不同的数据源 这样的好处是不用注解去切换数据源 1 引入驱动 span class token generics span c