每天一个小知识

mybatis plus + druid多数据源(使用dynamic实现)


)

引入pom:

    <!-- 动态数据源 -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
        <version>2.5.4</version>
    </dependency>

配置文件yml中:

spring:
autoconfigure:
#自动化配置 例外处理
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
datasource:
type: com.alibaba.druid.pool.DruidDataSource
#多数据源配置
dynamic:
primary: db1
datasource:
# 数据库1
db1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://xxxx:3306/xxx?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
username: xxx
password: xxxx
# 数据库2
db2:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://xxxx:3306/xxx?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
username: xxx
password: xxxx
#dynamic - 公共配置
druid:
initialSize: 5
minIdle: 5
maxActive: 30
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT ‘x’
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,slf4j,config
useGlobalDataSourceStat: true
stat:
log-slow-sql: true
merge-sql: true
slow-sql-millis: 10000

用法:在相应service类或方法上添加DS注解,如:

package com.tuijie.loanapi.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuijie.loanapi.mapper.TestUserMapper;
import com.tuijie.loanapi.model.mysql.TestUser;
import com.tuijie.loanapi.service.TestUserService;
import org.springframework.stereotype.Service;

/**

  • TestUserServiceImpl
  • 测试ServiceImpl
  • @version :
    */
    @Service
    @DS(“db2”)
    public class TestUserServiceImpl extends ServiceImpl<TestUserMapper, TestUser> implements TestUserService {
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值