SpringBoot Mybatis 多数据源 MySQL+Oracle+Redis

news2024/10/5 21:14:10

 一、背景

在SpringBoot Mybatis 项目中,需要连接 多个数据源,连接多个数据库,需要连接一个MySQL数据库和一个Oracle数据库和一个Redis

二、依赖 pom.xml

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- Oracle -->
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>19.8.0.0</version>
        </dependency>

        <!-- Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.4.4</version>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>
        <!--swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!--swagger-ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/cn.easyproject/orai18n -->
        <dependency>
            <groupId>cn.easyproject</groupId>
            <artifactId>orai18n</artifactId>
            <version>12.1.0.2.0</version>
        </dependency>

    </dependencies>

三、项目结构

四、application.yml

spring.datasource.url数据库的JDBC URL

spring.datasource.jdbc-url用来重写自定义连接池

Hikari没有url属性,但是有jdbcUrl属性,在这中情况下必须使用jdbc_url

server:
  port: 8080

spring:
  datasource:
    primary:
      jdbc-url: jdbc:mysql://localhost:3306/database_name
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver

    secondary:
      jdbc-url: jdbc:oracle:thin:@localhost:1521/ORCL
      username: root
      password: 123456
      driver-class-name: oracle.jdbc.driver.OracleDriver    

五、MySQL配置类

MysqlDataSourceConfig

使用注解@Primary配置默认数据源

package com.example.multipledata.config.mysqlconfig;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;


@Configuration
@MapperScan(basePackages = MysqlDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MysqlDataSourceConfig {
   
    static final String PACKAGE = "com.example.multipledata.mapper.mysqlmapper";

    static final String MAPPER_LOCATION = "classpath*:mapper/mysqlmapper/*.xml";

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

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

    @Primary
    @Bean(name = "mysqlSqlSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource mysqlDatasource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(mysqlDatasource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(MysqlDataSourceConfig.MAPPER_LOCATION)
        );
        return sessionFactory.getObject();
    }
}

六、Oracle配置类

OracleDataSourceConfig

package com.example.multipledata.config.oracleconfig;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;

@Configuration
@MapperScan(basePackages = OracleDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "oracleSqlSessionFactory")
public class OracleDataSourceConfig {

    static final String PACKAGE = "com.example.multipledata.mapper.oraclemapper";

    static final String MAPPER_LOCATION = "classpath*:mapper/oraclemapper/*.xml";

    @Bean(name = "oracleDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource oracleDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "oracleTransactionManager")
    public DataSourceTransactionManager oracleTransactionManager() {
        return new DataSourceTransactionManager(oracleDataSource());
    }

    @Bean(name = "oracleSqlSessionFactory")
    public SqlSessionFactory oracleSqlSessionFactory(@Qualifier("oracleDataSource") DataSource oracleDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(oracleDataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(OracleDataSourceConfig.MAPPER_LOCATION)
        );
        return sessionFactory.getObject();
    }
}

原文地址:

https://www.cnblogs.com/windy-xmwh/p/14748567.html

七、增加Redis连接

注意,我的Redis连接,使用了密码

7.1 新增依赖 pom.xml

pom.xml

        <!-- Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.4.4</version>
        </dependency>
        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </dependency>

7.2 配置Redis连接  application.yml

  spring:
    redis:
        host: host
        port: 6379
        password: 1

7.3 Redis 配置文件 RedisConfig

在config目录下,新增RedisConfig文件

package com.example.kyjjserver.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Value("${spring.redis.password}")
    private String redisPassword;

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisHost, redisPort);
        lettuceConnectionFactory.setPassword(redisPassword);
        return lettuceConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

7.4 操作Redis

7.4.1 封装操作方法

在service目录下,新增RedisService文件

package com.example.kyjjserver.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class RedisService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void deleteData(String key) {
        redisTemplate.delete(key);
    }

    public void deleteDataAll(String pattern) {
        Set<String> keys = redisTemplate.keys("*" + pattern + "*");
        if (keys != null) {
            redisTemplate.delete(keys);
        }
    }
}

7.4.2 调用方法,操作Redis库

1、注入

2、调用

@Component
public class DeleteRedisInfo {
    @Autowired
    private RedisService redisService;

    @Transactional
    public AAA deleteUser(xxx xxx){
        // 删除手机号
        redisService.deleteDataAll(xxx);
      


        return xxx;
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/952559.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【广州华锐互动】VR党建多媒体互动展厅:随时随地开展党史教育

随着科技的不断发展&#xff0c;虚拟现实(VR)技术已经逐渐渗透到各个领域&#xff0c;其中党建教育尤为受益。为了更好地传承红色基因&#xff0c;弘扬党的优良传统&#xff0c;广州华锐互动推出了VR党建多媒体互动展厅&#xff0c;让广大党员干部和人民群众通过现代科技手段&a…

CountDownLatch、Semaphore详解——深入探究CountDownLatch、Semaphore源码

这篇文章将会详细介绍基于AQS实现的两个并发类CountDownLatch和Semaphore&#xff0c;通过深入底层源代码讲解其具体实现。 目录 CountDownLatch countDown() await() Semaphore Semaphore类图 Semaphore的应用场景 acquire() tryAcquire() CountDownLatch /*** A synchroni…

Arduino程序设计(六)蜂鸣器实验

蜂鸣器实验 前言一、蜂鸣器简介1、蜂鸣器的工作原理2、有源蜂鸣器和无源蜂鸣器的区别3、蜂鸣器模块电路原理图 二、有源蜂鸣器实验有源蜂鸣器控制 三、无源蜂鸣器实验1、调节蜂鸣器输出频率2、无源蜂鸣器触发报警声3、无源蜂鸣器播放音乐 参考资料 前言 本文主要介绍两种蜂鸣器…

基于jeecg-boot的flowable流程审批时增加下一个审批人设置

更多nbcio-boot功能请看演示系统 gitee源代码地址 后端代码&#xff1a; https://gitee.com/nbacheng/nbcio-boot 前端代码&#xff1a;https://gitee.com/nbacheng/nbcio-vue.git 在线演示&#xff08;包括H5&#xff09; &#xff1a; http://122.227.135.243:9888 因为有时…

工服穿戴检测算法 工装穿戴识别算法

工服穿戴检测算法 工装穿戴识别算法利用yolo网络模型图像识别技术&#xff0c;工服穿戴检测算法 工装穿戴识别算法可以准确地识别现场人员是否穿戴了正确的工装&#xff0c;包括工作服、安全帽等。一旦检测到未穿戴的情况&#xff0c;将立即发出警报并提示相关人员进行整改。Yo…

python中的模块和包

模块 模块就是一个Python文件&#xff0c;里面有类、函数、变量等&#xff0c;我们可以拿过来用&#xff08;导入模块去使用&#xff09; 模块的导入方式 模块在使用前需要先导入。导入的语法如下: 常用的组合形式如&#xff1a; import 模块名from 模块名 import 类、变量、…

JavaScript闭包漏洞与修补措施

请先看下面一段代码 var obj (function () {var sonObj {a: 1,b: 2}return {getObj: function (v) {return sonObj[v]}}})()可以看出,这是一段很典型的js闭包代码,可以通过obj调用get方法传一个参数,如果传的是a就可以得到闭包内的对象sonObj.a var obj (function () {var s…

企业合规改革如何进行?

企业合规是现代商业运作中的重要议题&#xff0c;合规改革是促使企业适应法规变化、规范经营行为的必经之路。本文将介绍企业合规改革的步骤和方法&#xff0c;帮助企业建立健全的合规机制&#xff0c;增强竞争力&#xff0c;并赢得社会信任。 一、评估和分析 合规改革的第一…

明厨亮灶监控实施方案 opencv

明厨亮灶监控实施方案通过pythonopencv网络模型图像识别算法&#xff0c;一旦发现现场人员没有正确佩戴厨师帽或厨师服&#xff0c;及时发现明火离岗、不戴口罩、厨房抽烟、老鼠出没以及陌生人进入后厨等问题生成告警信息并进行提示。OpenCV是一个基于Apache2.0许可&#xff08…

eureka服务注册和服务发现

文章目录 问题实现以orderservice为例orderservice服务注册orderservice服务拉取 总结 问题 我们要在orderservice中根据查询到的userId来查询user&#xff0c;将user信息封装到查询到的order中。 一个微服务&#xff0c;既可以是服务提供者&#xff0c;又可以是服务消费者&a…

六、事务-1.简介

一、简介 例&#xff1a;张三转账1000元给李四 step1&#xff1a;查询张三账户余额是否有2000元 step2&#xff1a;若张三账户余额有2000元&#xff0c;张三账户余额-1000 step3&#xff1a;李四账户余额1000 若step2执行成功&#xff0c;step3执行失败&#xff0c;此时需要…

ToBeWritten之VSOC安全运营

也许每个人出生的时候都以为这世界都是为他一个人而存在的&#xff0c;当他发现自己错的时候&#xff0c;他便开始长大 少走了弯路&#xff0c;也就错过了风景&#xff0c;无论如何&#xff0c;感谢经历 转移发布平台通知&#xff1a;将不再在CSDN博客发布新文章&#xff0c;敬…

【ES】illegal_argument_exception“,“reason“:“Result window is too large

查询ES数据返回错误&#xff1a; {"root_cause":[{"type":"illegal_argument_exception","reason":"Result window is too large, from size must be less than or equal to: [10000] but was [999999]. See the scroll api for…

直播预告|博睿学院第四季即将开讲:博睿数据资深运维团队现身说法!

博睿学院第四季开讲啦&#xff01;本季博睿学院的课程将于本周四&#xff08;8月31日&#xff09;16点正式启动。本季我们邀请到了博睿数据平台支撑中心的四位资深运维专家现身说法&#xff0c;来为我们分享一体化智能可观测平台Bonree ONE的实践干货。 他们&#xff0c;见多识…

Gradio使用介绍

与他人分享你的机器学习模型、API或数据科学工作流的最佳方式之一&#xff0c;就是创建一个交互式应用程序&#xff0c;让用户或同事可以在他们的浏览器中尝试演示,Gradio是创建提供了用非常方便的方式快速创建一个前端交互应用&#xff0c;那如何使用Gradio呢&#xff1f;因为…

element侧边栏子路由点击不高亮问题

最近自己封装侧边栏 又碰到了点击子路由不高亮的问题 <template><div class"aside"><el-scrollbar :vertical"true" class"scrollbar_left_nav"><el-menu :default-active"defaultActive" :collapse"$stor…

MySQL高级篇_13_事务基础知识_尚硅谷_宋红康

MySQL高级篇_事务基础知识 1. 数据库事务概述1.1 存储引擎支持情况1.2 基本概念1.3 事务的ACID特性原子性&#xff08;atomicity&#xff09;一致性&#xff08;consistency&#xff09;隔离性&#xff08;isolation)持久性&#xff08;durability&#xff09; 1.4 事务的状态 …

Openlayers 教程 - 获取地图中心点、范围以及缩放等级

Openlayers 教程 - 获取地图中心点、范围以及缩放等级 核心代码完整代码&#xff1a;在线示例 之前项目中需要实时获取地图中心点以及范围&#xff0c;难度不高&#xff0c;为了方便使用&#xff0c;这里记录分享一下。 本文包括核心代码、完整代码以及在线示例。 核心代码 //…

Consul原理介绍

官方文档&#xff1a;https://www.consul.io/docs Raft动画演示&#xff1a;http://thesecretlivesofdata.com/raft/ 注册中心对比 Consul特点 服务发现、健康检查、Key/Value存储、安全服务通信&#xff08;TLS证书&#xff09;、多数据中心 架构 角色 数据中心 数据中心内…

windows 中pycharm中venv无法激活

1.用管理员身份打开Windows PowerShell 2.进入项目的&#xff1a;venv\Scripts 如&#xff1a;D: (1): cd .\project\venv\Scripts\ (2): 执行命令&#xff1a; Set-ExecutionPolicy RemoteSigned (3): 选择&#xff1a;Y (4): .\activate