spring boot動態(tài)切換數(shù)據(jù)源的實現(xiàn)
當數(shù)據(jù)量比較大的時候,我們就需要考慮讀寫分離了,也就是動態(tài)切換數(shù)據(jù)庫連接,對指定的數(shù)據(jù)庫進行操作。在spring中實現(xiàn)動態(tài)的切換無非就是利用AOP實現(xiàn)。我們可以使用mybatis-plus作者開發(fā)的插件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 #設(shè)置默認的數(shù)據(jù)源或者數(shù)據(jù)源組,默認值即為master strict: false #設(shè)置嚴格模式,默認false不啟動. 啟動后在未匹配到指定數(shù)據(jù)源時候會拋出異常,不啟動則使用默認數(shù)據(jù)源. datasource: master: #替換成自己的數(shù)據(jù)庫連接 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.Drivermybatis-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/**.xmllogging: 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;@Servicepublic 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')注解,來指定數(shù)據(jù)源
更換為自己的數(shù)據(jù)庫連接,以及建庫,運行resources/sql目錄下的sql文件然后啟動項目訪問http://127.0.0.1:8081/doc.html進行測試
到此這篇關(guān)于spring boot動態(tài)切換數(shù)據(jù)源的實現(xiàn)的文章就介紹到這了,更多相關(guān)spring boot動態(tài)切換數(shù)據(jù)源內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP基礎(chǔ)入門第三篇(ASP腳本基礎(chǔ))2. 詳解CSS不定寬溢出文本適配滾動3. python中if嵌套命令實例講解4. PHP與已存在的Java應(yīng)用程序集成5. 使用ProcessBuilder調(diào)用外部命令,并返回大量結(jié)果6. Python實現(xiàn)查找數(shù)據(jù)庫最接近的數(shù)據(jù)7. 使用css實現(xiàn)全兼容tooltip提示框8. CSS自定義滾動條樣式案例詳解9. Java之JSP教程九大內(nèi)置對象詳解(中篇)10. IDEA項目的依賴(pom.xml文件)導(dǎo)入問題及解決
