一,为什么要使用多个数据源?

1,什么情况下需要使用多个数据源?
当我们需要访问不同的数据库时,则需要配置配置多个数据源,
例如:电商的业务数据库(包括用户/商品/订单等)
           和统计数据库(按月日年的订单数量/金额等的统计)通常是分开到不同的数据库
所以我们需要在应用中创建多个数据库连接池
 
2,通常的作法:
     例如我们有两个数据库orderdb,goodsdb
    两个数据库的mapper.xml文件需要放到不同的目录下,
    通过给不同的目录配置不同的数据源,
    从而实现处理不同的业务功能
 

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,演示项目的相关信息

1,项目地址:

https://github.com/liuhongdi/multidruid

2,项目功能说明:

访问两个数据库,分别打印出两个库中商品和订单的信息

3,项目结构:如图:

三,配置文件说明:

1,pom.xml

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency> <!--druid begin-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.4.2</version>
</dependency>
<!--druid end--> <!--mybatis begin-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!--mybatis end--> <!--mysql begin-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mysql end-->

说明:因为给druid使用了log4j2日志,为避免冲突,

在spring-boot-starter-web中排除了spring-boot-starter-logging

2,application.properties:

#error
server.error.include-stacktrace=always
#error
logging.level.org.springframework.web=trace # 数据源goodsdb基本配置
spring.datasource.druid.goodsdb.username = root
spring.datasource.druid.goodsdb.password = lhddemo
spring.datasource.druid.goodsdb.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.druid.goodsdb.url = jdbc:mysql://127.0.0.1:3306/store?serverTimezone=UTC
spring.datasource.druid.goodsdb.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.goodsdb.initialSize = 5
spring.datasource.druid.goodsdb.minIdle = 5
spring.datasource.druid.goodsdb.maxActive = 20
spring.datasource.druid.goodsdb.maxWait = 60000
spring.datasource.druid.goodsdb.timeBetweenEvictionRunsMillis = 60000
spring.datasource.druid.goodsdb.minEvictableIdleTimeMillis = 300000
spring.datasource.druid.goodsdb.validationQuery = SELECT 1 FROM DUAL
spring.datasource.druid.goodsdb.testWhileIdle = true
spring.datasource.druid.goodsdb.testOnBorrow = false
spring.datasource.druid.goodsdb.testOnReturn = false
spring.datasource.druid.goodsdb.poolPreparedStatements = true
# 数据源orderdb基本配置
spring.datasource.druid.orderdb.username = root
spring.datasource.druid.orderdb.password = lhddemo
spring.datasource.druid.orderdb.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.druid.orderdb.url = jdbc:mysql://127.0.0.1:3306/orderdb?serverTimezone=UTC
spring.datasource.druid.orderdb.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.orderdb.initialSize = 5
spring.datasource.druid.orderdb.minIdle = 5
spring.datasource.druid.orderdb.maxActive = 20
spring.datasource.druid.orderdb.maxWait = 60000
spring.datasource.druid.orderdb.timeBetweenEvictionRunsMillis = 60000
spring.datasource.druid.orderdb.minEvictableIdleTimeMillis = 300000
spring.datasource.druid.orderdb.validationQuery = SELECT 1 FROM DUAL
spring.datasource.druid.orderdb.testWhileIdle = true
spring.datasource.druid.orderdb.testOnBorrow = false
spring.datasource.druid.orderdb.testOnReturn = false
spring.datasource.druid.orderdb.poolPreparedStatements = true # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filters = stat,wall,log4j2
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize = 20
spring.datasource.druid.useGlobalDataSourceStat = true
spring.datasource.druid.connectionProperties = druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 #druid sql firewall monitor
spring.datasource.druid.filter.wall.enabled=true #druid sql monitor
spring.datasource.druid.filter.stat.enabled=true
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=10000
spring.datasource.druid.filter.stat.merge-sql=true #druid uri monitor
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/* #druid session monitor
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.profile-enable=true #druid spring monitor
spring.datasource.druid.aop-patterns=com.druid.* #monintor,druid login user config
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.login-username=root
spring.datasource.druid.stat-view-servlet.login-password=root #mybatis
mybatis.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis.type-aliases-package=com.example.demo.mapper
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#log
logging.config = classpath:log4j2.xml

3,log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<!--只接受程序中DEBUG级别的日志进行处理-->
<ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n"/>
</Console>
<!--处理INFO级别的日志,并把该日志放到logs/info.log文件中-->
<RollingFile name="RollingFileInfo" fileName="./logs/info.log"
filePattern="logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz">
<Filters>
<ThresholdFilter level="INFO"/>
<ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/>
</Filters>
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n"/>
<Policies>
<SizeBasedTriggeringPolicy size="500 MB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
<!--处理WARN级别的日志,并把该日志放到logs/warn.log文件中-->
<RollingFile name="RollingFileWarn" fileName="./logs/warn.log"
filePattern="logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz">
<Filters>
<ThresholdFilter level="WARN"/>
<ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
</Filters>
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n"/>
<Policies>
<SizeBasedTriggeringPolicy size="500 MB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
<!--处理error级别的日志,并把该日志放到logs/error.log文件中-->
<RollingFile name="RollingFileError" fileName="./logs/error.log"
filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
<ThresholdFilter level="ERROR"/>
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n"/>
<Policies>
<SizeBasedTriggeringPolicy size="500 MB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
<!--druid的日志记录追加器-->
<RollingFile name="druidSqlRollingFile" fileName="./logs/druid-sql.log"
filePattern="logs/$${date:yyyy-MM}/api-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n"/>
<Policies>
<SizeBasedTriggeringPolicy size="500 MB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
</appenders>
<loggers>
<AsyncRoot level="info">
<appender-ref ref="Console"/>
<appender-ref ref="RollingFileInfo"/>
<appender-ref ref="RollingFileWarn"/>
<appender-ref ref="RollingFileError"/>
</AsyncRoot>
<!--记录druid-sql的记录-->
<AsyncLogger name="druid.sql.Statement" level="debug" additivity="false">
<appender-ref ref="druidSqlRollingFile"/>
</AsyncLogger>
</loggers>
</configuration>

4,数据库的相关业务表:

goods表

CREATE TABLE `goods` (
`goodsId` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`goodsName` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '' COMMENT 'name',
`subject` varchar(200) NOT NULL DEFAULT '' COMMENT '标题',
`price` decimal(15,2) NOT NULL DEFAULT '0.00' COMMENT '价格',
`stock` int(11) NOT NULL DEFAULT '0' COMMENT 'stock',
PRIMARY KEY (`goodsId`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='商品表'

goods表中的数据:

INSERT INTO `goods` (`goodsId`, `goodsName`, `subject`, `price`, `stock`) VALUES
(3, '100分电动牙刷', '好用到让你爱上刷牙', '59.00', 96);

order表:

CREATE TABLE `orderinfo` (
`orderId` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`orderSn` varchar(100) NOT NULL DEFAULT '' COMMENT '编号',
`orderTime` timestamp NOT NULL DEFAULT '1971-01-01 00:00:01' COMMENT '下单时间',
`orderStatus` tinyint(4) NOT NULL DEFAULT '0' COMMENT '状态:0,未支付,1,已支付,2,已发货,3,已退货,4,已过期',
`userId` int(12) NOT NULL DEFAULT '0' COMMENT '用户id',
`price` decimal(10,0) NOT NULL DEFAULT '0' COMMENT '价格',
`addressId` int(12) NOT NULL DEFAULT '0' COMMENT '地址',
PRIMARY KEY (`orderId`),
UNIQUE KEY `orderSn` (`orderSn`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='订单表'

order表中的数据:

INSERT INTO `orderinfo` (`orderId`, `orderSn`, `orderTime`, `orderStatus`, `userId`, `price`, `addressId`) VALUES
(77, '20200814171411660', '2020-08-14 09:14:12', 0, 8, '100', 0);

四,java代码说明:

1,GoodsdbSourceConfig.java

@Configuration
@MapperScan(basePackages = "com.multidruid.demo.mapper.goodsdb", sqlSessionTemplateRef = "goodsdbSqlSessionTemplate")
public class GoodsdbSourceConfig { @Bean
@Primary
@ConfigurationProperties("spring.datasource.druid.goodsdb")
public DataSource goodsdbDataSource() {
return DruidDataSourceBuilder.create().build();
} @Bean
@Primary
public SqlSessionFactory goodsdbSqlSessionFactory(@Qualifier("goodsdbDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/goodsdb/*.xml"));
return bean.getObject();
} @Bean
@Primary
public DataSourceTransactionManager goodsdbTransactionManager(@Qualifier("goodsdbDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean
@Primary
public SqlSessionTemplate goodsdbSqlSessionTemplate(@Qualifier("goodsdbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

说明:用basePackages指定mapper程序所在目录,

bean.setMapperLocations指定mapper的xml文件所在目录

2,OrderdbSourceConfig.java

@Configuration
@MapperScan(basePackages = "com.multidruid.demo.mapper.orderdb", sqlSessionTemplateRef = "orderdbSqlSessionTemplate")
public class OrderdbSourceConfig { @Bean
@ConfigurationProperties(prefix = "spring.datasource.druid.orderdb")
public DataSource orderdbDataSource() {
return DruidDataSourceBuilder.create().build();
} @Bean
public SqlSessionFactory orderdbSqlSessionFactory(@Qualifier("orderdbDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/orderdb/*.xml"));
return bean.getObject();
} @Bean
public DataSourceTransactionManager orderdbTransactionManager(@Qualifier("orderdbDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean
public SqlSessionTemplate orderdbSqlSessionTemplate(@Qualifier("orderdbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

说明:用basePackages指定mapper程序所在目录,

bean.setMapperLocations指定mapper的xml文件所在目录

主要是把两个数据源对应的mapper接口程序和mapper的xml文件隔离开

3,GoodsMapper.java

@Repository
@Mapper
public interface GoodsMapper {
Goods selectOneGoods(Long goodsId);
}

4,OrderMapper.java

@Repository
@Mapper
public interface OrderMapper {
Order selectOneOrder(Long orderId);
}

5,GoodsMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.multidruid.demo.mapper.goodsdb.GoodsMapper">
<select id="selectOneGoods" parameterType="long" resultType="com.multidruid.demo.pojo.Goods">
select * from goods where goodsId=#{goodsId}
</select>
</mapper>

6,OrderMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.multidruid.demo.mapper.orderdb.OrderMapper">
<select id="selectOneOrder" parameterType="long" resultType="com.multidruid.demo.pojo.Order">
select * from orderinfo where orderId=#{orderId}
</select>
</mapper>

7,HomeController.java

@Controller
@RequestMapping("/home")
public class HomeController { @Resource
private GoodsMapper goodsMapper; @Resource
private OrderMapper orderMapper; //商品详情 参数:商品id
@GetMapping("/goodsinfo")
@ResponseBody
public Goods goodsInfo(@RequestParam(value="goodsid",required = true,defaultValue = "0") Long goodsId) {
Goods goods = goodsMapper.selectOneGoods(goodsId);
return goods;
} //订单详情 参数:订单id
@GetMapping("/orderinfo")
@ResponseBody
public Order orderInfo(@RequestParam(value="orderid",required = true,defaultValue = "0") Long orderId) {
Order order = orderMapper.selectOneOrder(orderId);
return order;
}
}

8,Goods/Order  两个pojo类很简单,不列出了,大家可以访问github查看

五,测试效果:

1,查询商品信息,访问:

http://127.0.0.1:8080/home/goodsinfo?goodsid=3

返回:

{"goodsId":3,"goodsName":"100分电动牙刷","subject":"好用到让你爱上刷牙","price":59.00,"stock":96}

2,查询订单信息,访问:

http://127.0.0.1:8080/home/orderinfo?orderid=77

返回:

{"orderId":77,"orderSn":"20200814171411660","orderTime":"2020-08-14 17:14:12","orderStatus":0,"userId":8,"price":100}

3,查看druid监控页面中连接到的数据源

可以看到已连接到的两个数据源

六,查看spring boot的版本

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)

spring boot:使mybatis访问多个druid数据源(spring boot 2.3.2)的更多相关文章

  1. spring boot:使用mybatis访问多个mysql数据源/查看Hikari连接池的统计信息(spring boot 2.3.1)

    一,为什么要访问多个mysql数据源? 实际的生产环境中,我们的数据并不会总放在一个数据库, 例如:业务数据库:存放了用户/商品/订单 统计数据库:按年.月.日的针对用户.商品.订单的统计表 因为统计 ...

  2. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-1.整合Mybatis访问数据库和阿里巴巴数据源

    笔记 1.整合Mybatis访问数据库和阿里巴巴数据源     简介:整合mysql 加入mybatis依赖,和加入alibaba druid数据源 1.加入依赖(可以用 http://start.s ...

  3. spring boot:配置shardingsphere(sharding jdbc)使用druid数据源(druid 1.1.23 / sharding-jdbc 4.1.1 / mybatis / spring boot 2.3.3)

    一,为什么要使用druid数据源? 1,druid的优点 Druid是阿里巴巴开发的号称为监控而生的数据库连接池 它的优点包括: 可以监控数据库访问性能 SQL执行日志 SQL防火墙 但spring ...

  4. Spring boot教程mybatis访问MySQL的尝试

    Windows 10家庭中文版,Eclipse,Java 1.8,spring boot 2.1.0,mybatis-spring-boot-starter 1.3.2,com.github.page ...

  5. struts2与spring整合问题,访问struts2链接时,spring会负责创建Action

    每次访问一次链接,spring会创建一个对象,并将链接所带的参数注入到Action的变量中(如何做到的呐) 因为: struts2的action每次访问都重新创建一个对象,那spring的ioc是怎么 ...

  6. spring boot集成mybatis(1)

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. spring boot集成mybatis(2) - 使用pagehelper实现分页

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  8. spring boot集成mybatis(3) - mybatis generator 配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  9. spring boot配置mybatis和事务管理

    spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...

随机推荐

  1. 【NOIP2013模拟】黑魔法师之门

    题目描述 经过了16个工作日的紧张忙碌,未来的人类终于收集到了足够的能源.然而在与Violet星球的战争中,由于Z副官的愚蠢,地球的领袖applepi被邪恶的黑魔法师Vani囚禁在了Violet星球. ...

  2. Django 页面之间传递MySql数据表(Django八)

    之前实现了页面传递多个参数,但没有实现页面间传递一整个数据表 session传递几个参数:https://blog.csdn.net/qq_38175040/article/details/10496 ...

  3. 程序员你是如何降低NPE的?

    程序员,如果系统突然报了一个空指针异常,你肯定像吞了一只苍蝇一样尴尬. 那么如何在日常开发过程中降低NPE? 问题 回答 现状 返回空值会出现大量的空指针异常 目的 改进方法的返回值,降低出现空指针异 ...

  4. 关于java基础_方法的简单习题

    package day05; import java.util.Arrays; /** * 方法作业 * @author ASUS * */ public class Demo6 { /* * 1.定 ...

  5. java8--排序

    排序的传统的写法是: Collections.sort( SortTest.users, new Comparator<User>() { @Override public int com ...

  6. 深入理解java虚拟机--垃圾收集器

    对象的销毁 对象的finalize方法只会执行一次,在finalize里可以自救不被销毁,二次被主动gc,必定会销毁 类销毁

  7. 最全总结 | 聊聊 Python 数据处理全家桶(Sqlite篇)

    1. 前言 上篇文章 聊到 Python 处理 Mysql 数据库最常见的两种方式,本篇文章继续说另外一种比较常用的数据库:Sqlite Sqlite 是一种 嵌入式数据库,数据库就是一个文件,体积很 ...

  8. ES6 常用总结——第三章(数组、函数、对象的扩展)

    1.1. Array.from() Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括ES6新增的数据结 ...

  9. dubbo学习(九)dubbo监控中心

    安装与配置 下载地址:https://github.com/apache/dubbo-admin/tree/master(包含管理控制台和监控中心) PS:  下载前要选择master分支以后再进行下 ...

  10. 学习OpenGL

    重要!!! OpenGL新人一枚,希望可以再此和大家分享有用的知识,少走弯路 文章会定期更新,把前面几段已经整理过的知识更完后,接下来每周至少会更两次. 文章如果有不对的,理解错误的地方,也非常希望在 ...