SpringBoot+aop實現主從數據庫的讀寫分離

讀寫分離的作用是為了緩解寫庫,也就是主庫的壓力,但一定要基于數據一致性的原則,就是保證主從庫之間的數據一定要一致。如果一個方法涉及到寫的邏輯,那么該方法里所有的數據庫操作都要走主庫。

一、環境部署

  • 數據庫:MySql
  • 2個,一主一從
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`user_id` bigint(20) NOT NULL COMMENT '用戶id',`user_name` varchar(255) DEFAULT '' COMMENT '用戶名稱',`user_phone` varchar(50) DEFAULT '' COMMENT '用戶手機',`address` varchar(255) DEFAULT '' COMMENT '住址',`weight` int(3) NOT NULL DEFAULT '1' COMMENT '權重,大者優先',`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `user` VALUES ('1196978513958141952', '測試1', '18826334748', '廣州市海珠區', '1', '2019-11-20 10:28:51', '2019-11-22 14:28:26');
INSERT INTO `user` VALUES ('1196978513958141953', '測試2', '18826274230', '廣州市天河區', '2', '2019-11-20 10:29:37', '2019-11-22 14:28:14');
INSERT INTO `user` VALUES ('1196978513958141954', '測試3', '18826273900', '廣州市天河區', '1', '2019-11-20 10:30:19', '2019-11-22 14:28:30');

二、依賴

<dependencies><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>2.1.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version></dependency><!-- 動態數據源 所需依賴 ### start--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId><scope>provided</scope></dependency><!-- 動態數據源 所需依賴 ### end--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.4</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
</dependencies>

在這里插入圖片描述

三、application.yml配置主從數據源

server:port: 8001
spring:jackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Drivermaster:url: jdbc:mysql://127.0.0.1:3307/user?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=trueusername: rootpassword:slave:url: jdbc:mysql://127.0.0.1:3308/user?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=trueusername: rootpassword:

四、Config配置

@Getter
public enum DynamicDataSourceEnum {MASTER("master"),SLAVE("slave");private String dataSourceName;DynamicDataSourceEnum(String dataSourceName) {this.dataSourceName = dataSourceName;}
}
@Configuration
@MapperScan(basePackages = "com.xjt.proxy.mapper", sqlSessionTemplateRef = "sqlTemplate")
public class DataSourceConfig{//主庫@Bean@ConfigurationProperties(prefix = "spring.datasource.master")public DataSource masterDb(){return DruidDataSourceBuilder.create().build();}//從庫@Bean@ConditionalOnProperty(prefix = "spring.datasource", name = "slave", matchIfMissing = true)@ConfigurationProperties(prefix = "spring.datasource.slave")public DataSource slaveDb() {return DruidDataSourceBuilder.create().build();}//主從動態配置@Beanpublic DynamicDataSource dynamicDb(@Qualifier("masterDb") DataSource masterDataSource,@Autowired(required = false) @Qualifier("slaveDb") DataSource slaveDataSource){DynamicDataSource dynamicDataSource = new DynamicDataSource();Map<Object,Object> targetDataSources = new HashMap<>();targetDataSources.put(DynamicDataSourceEnum.MASTER.getDataSourceName(), masterDataSource);if(slaveDataSource != null){targetDataSources.put(DynamicDataSourceEnum.SLAVE.getDataSourceName(), slaveDataSource);}dynamicDataSource.setTargetDataSources(targetDataSources);dynamicDataSource.setDefaultTargetDataSource(masterDataSource);return dynamicDataSource;}@Beanpublic SqlSessionFactory sessionFactory(){SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper.xml"));bean.setDataSource(dynamicDataSource);return bean.getObject();}@Beanpublic SqlSessionTemplate sqlTemplate(){return new SqlSessionTemplate(sqlSessionFactory);}@Bean(name = "dataourceTx")public DataSourceTransactionManager dataSourceTx(){DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();dataSourceTransactionManager.setDataSource(dynamicDataSource);return dataSourceTransactionManager;}
}

五、設置路由

為了方便查找對應的數據源,我們可以用ThreadLocal保存數據源的信息到每個線程中,方便我們需要時獲取

pubic class DataSourceContextHolder{private static final ThreadLocal<String> DYNAMIC_DATASOURCE_CONTEXT = new ThreadLocal<>();public static void set(String datasourceType) {DYNAMIC_DATASOURCE_CONTEXT.set(datasourceType);}public static String get() {return DYNAMIC_DATASOURCE_CONTEXT.get();}public static void clear() {DYNAMIC_DATASOURCE_CONTEXT.remove();}
}

AbstractRoutingDataSource的作用是基于查找key路由到對應的數據源,它內部維護了一組目標數據源,并且做了路由key與目標數據源之間的映射,提供基于key查找數據源的方法。

public class DynamicDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return DataSourceContextHolder.get();}
}

六、數據源的注解

方便切換數據源,注解中包含數據源對應的枚舉值,默認是主庫

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface DataSourceSelector {DynamicDataSourceEnum value() default DynamicDataSourceEnum.MASTER;boolean clear() default true;
}

七、Aop切換數據源

定義一個aop類,對有注解的方法做切換數據源的操作

@Slf4j
@Aspect
@Order(value = 1)
@Component
public class DataSourceContextAop {@Around("@annotation(com.xjt.proxy.dynamicdatasource.DataSourceSelector)")public Object setDynamicDataSource(ProceedingJoinPoint pjp) throws Throwable {boolean clear = true;try {Method method = this.getMethod(pjp);DataSourceSelector dataSourceImport = method.getAnnotation(DataSourceSelector.class);//獲取注解標注的方法clear = dataSourceImport.clear();DataSourceContextHolder.set(dataSourceImport.value().getDataSourceName());log.info("========數據源切換至:{}", dataSourceImport.value().getDataSourceName());return pjp.proceed();} finally {if (clear) {DataSourceContextHolder.clear();}}}private Method getMethod(JoinPoint pjp) {MethodSignature signature = (MethodSignature)pjp.getSignature();return signature.getMethod();}}

八、測試

寫好Service文件,包含讀取和更新兩個方法

@Service
public class UserService {@Autowiredprivate UserMapper userMapper;@DataSourceSelector(value = DynamicDataSourceEnum.SLAVE)public List<User> listUser() {List<User> users = userMapper.selectAll();return users;}@DataSourceSelector(value = DynamicDataSourceEnum.MASTER)public int update() {User user = new User();user.setUserId(Long.parseLong("1196978513958141952"));user.setUserName("修改后的名字2");return userMapper.updateByPrimaryKeySelective(user);}@DataSourceSelector(value = DynamicDataSourceEnum.SLAVE)public User find() {User user = new User();user.setUserId(Long.parseLong("1196978513958141952"));return userMapper.selectByPrimaryKey(user);}
}

根據方法上的注解可以看出,讀的方法走從庫,更新的方法走主庫,更新的對象是userId為1196978513958141953 的數據

@RunWith(SpringRunner.class)
@SpringBootTest
class UserServiceTest {@AutowiredUserService userService;@Testvoid listUser() {List<User> users = userService.listUser();for (User user : users) {System.out.println(user.getUserId());System.out.println(user.getUserName());System.out.println(user.getUserPhone());}}@Testvoid update() {userService.update();User user = userService.find();System.out.println(user.getUserName());}
}

讀取方法
在這里插入圖片描述

更新方法
在這里插入圖片描述
執行之后,比對數據庫就可以發現主從庫都修改了數據,說明我們的讀寫分離是成功的。當然,更新方法可以指向從庫,這樣一來就只會修改到從庫的數據,而不會涉及到主庫。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/717425.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/717425.shtml
英文地址,請注明出處:http://en.pswp.cn/news/717425.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

深入了解Java虛擬機(JVM)

Java虛擬機&#xff08;JVM&#xff09;是Java程序運行的核心組件&#xff0c;它負責解釋執行Java字節碼&#xff0c;并在各種平臺上執行。JVM的設計使得Java具有跨平臺性&#xff0c;開發人員只需編寫一次代碼&#xff0c;就可以在任何支持Java的系統上運行。我們剛開始學習Ja…

【leetcode】用隊列實現棧

大家好&#xff0c;我是蘇貝&#xff0c;本篇博客帶大家刷題&#xff0c;如果你覺得我寫的還不錯的話&#xff0c;可以給我一個贊&#x1f44d;嗎&#xff0c;感謝?? 點擊查看題目 思路: 在做此題之前&#xff0c;我們先要實現隊列&#xff0c;這在上個博客中已經寫過&#…

學習人工智能的方法及方向!

目錄 一、第一部分&#xff1a;了解人工智能 二、人工智能學習路線圖 三、職業規劃 四、未來展望 五、總結 在這個信息爆炸的時代&#xff0c;想要系統性地學習人工智能&#xff08;AI&#xff09;并找到對應方向的工作&#xff0c;你需要一個明確的學習路徑和職業規劃。本…

復合機器人是一種集成了移動機器人

復合機器人是一種集成了移動機器人、協作機器人和機器視覺等多項功能的新型機器人。它的開發目的是為了解決工廠物流中最后一米的問題&#xff0c;提供智能搬運解決方案。復合機器人不僅集成了自主移動機器人&#xff08;AMR&#xff09;、機械臂等工作單元&#xff0c;還使用了…

Java電梯模擬

Java電梯模擬 文章目錄 Java電梯模擬前言一、UML類圖二、代碼三、測試 前言 此程序為單線程簡單模擬電梯(初版)&#xff0c;如果存在問題或者設計不合理的地方&#xff0c;請大家幫忙指出。 一、UML類圖 二、代碼 電梯調度器 package cn.xx.evevator;import java.util.*;pub…

#LLM入門|Prompt#2.1_第二部分:搭建基于 ChatGPT 的問答系統_簡介_Introduction

《第二部分&#xff1a;搭建基于 ChatGPT 的問答系統》&#xff01; 本部分基于吳恩達老師與OpenAI合作開發的課程《Building Systems with the ChatGPT API》創作&#xff0c;旨在指導開發者基于ChatGPT的API進行智能問答系統的構建。 課程內容 課程背景&#xff1a; 使用C…

Web3游戲基礎設施提供商Stardust為Sui上的游戲開發者提供支持

Stardust將其在錢包服務&#xff08;wallets-as-a-service&#xff09;基礎設施和用戶獲取平臺方面的專業知識帶到了Sui&#xff0c;為游戲開發者提供了關鍵的幫助&#xff0c;以吸引玩家。近日&#xff0c;Stardust公司宣布將為Sui游戲開發者調整其成熟的錢包服務&#xff08;…

MySQL:開始深入其數據(四)select子查詢

select眼熟吧?(都三節了) 又開始學習了 在 MySQL 中&#xff0c;子查詢&#xff08;subquery&#xff09;是指在一個查詢內嵌套另一個完整的 SELECT 語句。子查詢可以嵌套在 SELECT、INSERT、UPDATE、DELETE 語句中&#xff0c;用于從內部查詢結果中獲取數據&#xff0c;進而完…

vue3 的await async

在 Vue 3&#xff08;以及大多數現代的 JavaScript 環境中&#xff09;中&#xff0c;async 和 await 是用來處理異步操作的關鍵字。這些關鍵字使你能夠以同步的方式編寫異步代碼&#xff0c;使代碼更加易讀、易寫&#xff0c;并且有助于管理異步流程。 async async 關鍵字用…

基于springboot的寵物咖啡館平臺的設計與實現論文

基于Spring Boot的寵物咖啡館平臺的設計與實現 摘要 隨著信息技術在管理上越來越深入而廣泛的應用&#xff0c;管理信息系統的實施在技術上已逐步成熟。本文介紹了基于Spring Boot的寵物咖啡館平臺的設計與實現的開發全過程。通過分析基于Spring Boot的寵物咖啡館平臺的設計與…

每日一題——LeetCode1566.重復至少K次且長度為M的模式

方法一 暴力枚舉 var containsPattern function(arr, m, k) {const n arr.length;for (let l 0; l < n - m * k; l) {let offset;for (offset 0; offset < m * k; offset) {if (arr[l offset] ! arr[l offset % m]) {break;}}if (offset m * k) {return true;}}r…

k8s 網絡概念與策略控制

一、Kubernetes 基本網絡模型 Kubernetes 的容器網絡模型可以把它歸結為約法三章和四大目標。 1、約法三章 約法三章確保了Kubernetes容器網絡模型的基本特性&#xff1a; ① 任意兩個 pod 之間可以直接通信&#xff1a;在Kubernetes中&#xff0c;每個 Pod 都被分配了一個…

題記(47)--連續因子

目錄 一、題目內容 二、輸入描述 三、輸出描述 四、輸入輸出示例 五、完整C語言代碼 一、題目內容 一個正整數 N 的因子中可能存在若干連續的數字。例如 630 可以分解為 3567&#xff0c;其中 5、6、7 就是 3 個連續的數字。給定任一正整數 N&#xff0c;要求編寫程序求出…

React-router的創建和第一個組件

需要先學react框架 首先&#xff1a;找到一個文件夾&#xff0c;在文件夾出打開cmd窗口&#xff0c;輸入如下圖的口令 npx create-react-app demo 然后等待安裝 安裝完成 接下來進入創建的demo實例 cd demo 然后可以用如下方式打開vscode code . 注意&#xff1a;不要忽略點號與…

Vue--》打造簡易直播應用平臺項目實戰

今天開始使用 vue3 + ts 搭建一個簡易直播應用平臺項目,因為文章會將項目的每一個地方代碼的書寫都會講解到,所以本項目會分成好幾篇文章進行講解,我會在最后一篇文章中會將項目代碼開源到我的github上,大家可以自行去進行下載運行,希望本文章對有幫助的朋友們能多多關注本…

AWS對文本進行語言識別

AWS提供了名為Amazon Comprehend 的服務&#xff0c;它支持對文本進行語言識別。Amazon Comprehend 是一項自然語言處理&#xff08;NLP&#xff09;服務&#xff0c;它可以用于分析文本并提取有關文本內容的信息。 我們可以通過使用 Amazon Comprehend API 輕松地集成這些功能…

機械臂與tftp

機械臂&#xff1a; #include<myhead.h> #define SER_IP "192.168.126.2" #define SER_PORT 8888#define CLI_IP "192.168.252.165" #define CLI_PORT 9999int main(int argc, const char *argv[]) {int cfdsocket(AF_INET,SOCK_STREAM,0);if(cfd-…

支持向量機 SVM | 線性可分:公式推導

目錄 一. SVM的優越性二. SVM算法推導小節概念 在開始講述SVM算法之前&#xff0c;我們先來看一段定義&#xff1a; 支持向量機(Support VecorMachine, SVM)本身是一個二元分類算法&#xff0c;支持線性分類和非線性分類的分類應用&#xff0c;同時通過OvR或者OvO的方式可以應用…

安裝Docker及DockerCompose

0.安裝Docker Docker 分為 CE 和 EE 兩大版本。CE 即社區版&#xff08;免費&#xff0c;支持周期 7 個月&#xff09;&#xff0c;EE 即企業版&#xff0c;強調安全&#xff0c;付費使用&#xff0c;支持周期 24 個月。 Docker CE 分為 stable test 和 nightly 三個更新頻道…

10.輪廓系數-機器學習模型性能的常用的評估指標

輪廓系數&#xff08;Silhouette Coefficient&#xff09;是評估聚類算法效果的常用指標之一。它結合了聚類的凝聚度&#xff08;Cohesion&#xff09;和分離度&#xff08;Separation&#xff09;&#xff0c;能夠量化聚類結果的緊密度和分離度。 背景 1.聚類分析的背景 在…