dynamic-datasource-spring-boot-starter 是一个基于springboot的快速集成多数据源的启动器,具有支持 数据源分组、自定义注解、自定义数据源来源等特性,更多详情可以访问官网
1. 引入核心依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.9</version>
</dependency>
2. application.yml配置
server:
port: 8226
spring:
application:
name: springboot-dynamic-mybatis-plus
datasource:
type: com.alibaba.druid.pool.DruidDataSource
dynamic:
primary: master
strict: true #严格匹配数据源
datasource:
master:
url: jdbc:mysql://localhost:3306/dynamic-master?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: LIU81&yj
driver-class-name: com.mysql.cj.jdbc.Driver
slave:
url: jdbc:mysql://localhost:3306/dynamic-slave?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: LIU81&yj
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
initial-size: 5 #初始连接数
min-idle: 10 #最小连接池
max-active: 20 #最大连接池
max-wait: 60000 #连接等待超时时间
time-between-eviction-runs-millis: 60000 #检测间隔时间,毫秒
min-evictable-idle-time-millis: 300000 #连接池最小生存时间,毫秒
max-evictable-idle-time-millis: 900000 #连接池最大生存时间,毫秒
validation-query: SELECT 1 FROM DUAL #连接检测
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3. 引入注解动态切换数据源
只需要在业务接口实现类上引入@DS()注解即可
@Service
@DS(value = "master")
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
}
若需要使用到事务,只需要在最外层加注解@DSTransactional即可
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/76761.html