spring boot动态切换数据源的实现
当数据量比较大的时候,我们就需要考虑读写分离了,也就是动态切换数据库连接,对指定的数据库进行操作。在spring中实现动态的切换无非就是利用AOP实现。我们可以使用mybatis-plus作者开发的插件dynamic-datasource-spring-boot-starter。
demo地址:https://github.com/songshijun1995/spring-boot-dynamic-demo
新建项目引入依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency>
配置yml
server: port: 8081 servlet: context-path: / spring: application: name: spring-boot-dynamic-demo datasource: dynamic: primary: master #设置默认的数据源或者数据源组,默认值即为master strict: false #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源. datasource: master: #替换成自己的数据库连接 url: jdbc:mysql://127.0.0.1:3306/dynamic1?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowMultiQueries=true&rewriteBatchedStatements=true username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver slave_1: url: jdbc:mysql://127.0.0.1:3306/dynamic2?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowMultiQueries=true&rewriteBatchedStatements=true username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl global-config: db-config: logic-delete-value: 1 logic-not-delete-value: 0 logic-delete-field: deleted mapper-locations: classpath:/mapper/**.xml logging: level: ROOT: INFO com.dynamic.dynamicdemo: DEBUG pattern: file: '%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{50} - %msg%n' file: name: ${logging.file.path}/${spring.application.name}.log path: /home/logs/${spring.application.name} logback: rollingpolicy: max-file-size: 10MB max-history: 30
mybatis-plus和swagger配置我就不多说了,demo里都有
如何使用
package com.dynamic.dynamicdemo.service.impl; import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.dynamic.dynamicdemo.dto.PageRequest; import com.dynamic.dynamicdemo.dto.UserInfoRequest; import com.dynamic.dynamicdemo.entities.BaseEntity; import com.dynamic.dynamicdemo.entities.UserInfo; import com.dynamic.dynamicdemo.mapper.UserInfoMapper; import com.dynamic.dynamicdemo.service.UserInfoService; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService { @DS("master") @Transactional(rollbackFor = Exception.class) @Override public String saveUser(UserInfoRequest request) { UserInfo userInfo = new UserInfo(); BeanUtils.copyProperties(request, userInfo); boolean save = save(userInfo); if (!save) { throw new RuntimeException("添加用户失败"); } return "添加用户成功"; } @DS("slave_1") @Override public IPage<UserInfo> pageUser(PageRequest request) { return page(new Page<>(request.getPageNum(), request.getPageSize()), Wrappers.<UserInfo>lambdaQuery().orderByDesc(BaseEntity::getCreateTime)); } }
在方法上或者类上加@DS("master")注解,来指定数据源
更换为自己的数据库连接,以及建库,运行resources/sql目录下的sql文件
然后启动项目访问http://127.0.0.1:8081/doc.html进行测试
到此这篇关于spring boot动态切换数据源的实现的文章就介绍到这了,更多相关spring boot动态切换数据源内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)