文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

SpringBoot Mybatis 多数据源 MySQL+Oracle+Redis

2023-09-20 13:50

关注

 一、背景

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

二、依赖 pom.xml

                     org.springframework.boot            spring-boot-starter-web                            org.springframework.boot            spring-boot-starter-test            test                                    mysql            mysql-connector-java            8.0.26                            org.springframework.boot            spring-boot-starter-jdbc                            org.mybatis.spring.boot            mybatis-spring-boot-starter            1.3.2                                    com.oracle.database.jdbc            ojdbc8            19.8.0.0                                    org.springframework.boot            spring-boot-starter-data-redis            2.4.4                                    org.projectlombok            lombok            1.18.16            provided                            javax.persistence            javax.persistence-api            2.2                                    io.springfox            springfox-swagger2            2.9.2                                    io.springfox            springfox-swagger-ui            2.9.2                                    cn.easyproject            orai18n            12.1.0.2.0            

三、项目结构

四、application.yml

spring.datasource.url数据库的JDBC URL

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

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

server:  port: 8080spring:  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

                            org.springframework.boot            spring-boot-starter-data-redis            2.4.4                            io.lettuce            lettuce-core        

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;@Configurationpublic 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 redisTemplate(RedisConnectionFactory redisConnectionFactory) {        RedisTemplate 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;@Servicepublic class RedisService {    private final RedisTemplate redisTemplate;    @Autowired    public RedisService(RedisTemplate redisTemplate) {        this.redisTemplate = redisTemplate;    }    public void deleteData(String key) {        redisTemplate.delete(key);    }    public void deleteDataAll(String pattern) {        Set keys = redisTemplate.keys("*" + pattern + "*");        if (keys != null) {            redisTemplate.delete(keys);        }    }}

7.4.2 调用方法,操作Redis库

注入

调用

@Componentpublic class DeleteRedisInfo {    @Autowired    private RedisService redisService;    @Transactional    public AAA deleteUser(xxx xxx){        // 删除手机号        redisService.deleteDataAll(xxx);              return xxx;    }}

来源地址:https://blog.csdn.net/qq_39208536/article/details/132575001

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-数据库
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯