成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Spring Boot + MyBatis + MySQL 實(shí)現(xiàn)讀寫(xiě)分離!

開(kāi)發(fā) 后端 MySQL
讀寫(xiě)分離要做的事情就是對(duì)于一條SQL該選擇哪個(gè)數(shù)據(jù)庫(kù)去執(zhí)行,至于誰(shuí)來(lái)做選擇數(shù)據(jù)庫(kù)這件事兒,無(wú)非兩個(gè),要么中間件幫我們做,要么程序自己做。

 1、引言

讀寫(xiě)分離要做的事情就是對(duì)于一條SQL該選擇哪個(gè)數(shù)據(jù)庫(kù)去執(zhí)行,至于誰(shuí)來(lái)做選擇數(shù)據(jù)庫(kù)這件事兒,無(wú)非兩個(gè),要么中間件幫我們做,要么程序自己做。

因此,一般來(lái)講,讀寫(xiě)分離有兩種實(shí)現(xiàn)方式。第一種是依靠中間件(比如:MyCat),也就是說(shuō)應(yīng)用程序連接到中間件,中間件幫我們做SQL分離;第二種是應(yīng)用程序自己去做分離。這里我們選擇程序自己來(lái)做,主要是利用Spring提供的路由數(shù)據(jù)源,以及AOP

然而,應(yīng)用程序?qū)用嫒プ鲎x寫(xiě)分離最大的弱點(diǎn)(不足之處)在于無(wú)法動(dòng)態(tài)增加數(shù)據(jù)庫(kù)節(jié)點(diǎn),因?yàn)閿?shù)據(jù)源配置都是寫(xiě)在配置中的,新增數(shù)據(jù)庫(kù)意味著新加一個(gè)數(shù)據(jù)源,必然改配置,并重啟應(yīng)用。當(dāng)然,好處就是相對(duì)簡(jiǎn)單。

2、AbstractRoutingDataSource

基于特定的查找key路由到特定的數(shù)據(jù)源。它內(nèi)部維護(hù)了一組目標(biāo)數(shù)據(jù)源,并且做了路由key與目標(biāo)數(shù)據(jù)源之間的映射,提供基于key查找數(shù)據(jù)源的方法。

3、實(shí)踐

3.1. maven依賴(lài) 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  4.     <modelVersion>4.0.0</modelVersion>  
  5.     <groupId>com.cjs.example</groupId>  
  6.     <artifactId>cjs-datasource-demo</artifactId>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <packaging>jar</packaging>  
  9.     <name>cjs-datasource-demo</name>  
  10.     <description></description>  
  11.     <parent>  
  12.         <groupId>org.springframework.boot</groupId>  
  13.         <artifactId>spring-boot-starter-parent</artifactId>  
  14.         <version>2.0.5.RELEASE</version>  
  15.         <relativePath/> <!-- lookup parent from repository -->  
  16.     </parent>  
  17.     <properties>  
  18.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  19.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
  20.         <java.version>1.8</java.version>  
  21.     </properties>  
  22.     <dependencies>  
  23.         <dependency>  
  24.             <groupId>org.springframework.boot</groupId>  
  25.             <artifactId>spring-boot-starter-aop</artifactId>  
  26.         </dependency>  
  27.         <dependency>  
  28.             <groupId>org.springframework.boot</groupId>  
  29.             <artifactId>spring-boot-starter-jdbc</artifactId>  
  30.         </dependency>  
  31.         <dependency>  
  32.             <groupId>org.springframework.boot</groupId>  
  33.             <artifactId>spring-boot-starter-web</artifactId>  
  34.         </dependency>  
  35.         <dependency>  
  36.             <groupId>org.mybatis.spring.boot</groupId>  
  37.             <artifactId>mybatis-spring-boot-starter</artifactId>  
  38.             <version>1.3.2</version>  
  39.         </dependency>  
  40.         <dependency>  
  41.             <groupId>org.apache.commons</groupId>  
  42.             <artifactId>commons-lang3</artifactId>  
  43.             <version>3.8</version>  
  44.         </dependency>  
  45.         <dependency>  
  46.             <groupId>mysql</groupId>  
  47.             <artifactId>mysql-connector-java</artifactId>  
  48.             <scope>runtime</scope>  
  49.         </dependency>  
  50.         <dependency>  
  51.             <groupId>org.springframework.boot</groupId>  
  52.             <artifactId>spring-boot-starter-test</artifactId>  
  53.             <scope>test</scope>  
  54.         </dependency>  
  55.     </dependencies>  
  56.     <build>  
  57.         <plugins>  
  58.             <plugin>  
  59.                 <groupId>org.springframework.boot</groupId>  
  60.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  61.             </plugin>  
  62.             <!--<plugin>  
  63.                 <groupId>org.mybatis.generator</groupId>  
  64.                 <artifactId>mybatis-generator-maven-plugin</artifactId>  
  65.                 <version>1.3.5</version>  
  66.                 <dependencies>  
  67.                     <dependency>  
  68.                         <groupId>mysql</groupId>  
  69.                         <artifactId>mysql-connector-java</artifactId>  
  70.                         <version>5.1.46</version>  
  71.                     </dependency>  
  72.                 </dependencies>  
  73.                 <configuration>  
  74.                     <configurationFile>${basedir}/src/main/resources/myBatisGeneratorConfig.xml</configurationFile>  
  75.                     <overwrite>true</overwrite>  
  76.                 </configuration>  
  77.                 <executions>  
  78.                     <execution>  
  79.                         <id>Generate MyBatis Artifacts</id>  
  80.                         <goals>  
  81.                             <goal>generate</goal>  
  82.                         </goals>  
  83.                     </execution>  
  84.                 </executions>  
  85.             </plugin>-->  
  86.         </plugins>  
  87.     </build>  
  88. </project> 

3.2. 數(shù)據(jù)源配置

application.yml 

  1. spring:  
  2.   datasource:  
  3.     master:  
  4.       jdbc-url: jdbc:mysql://192.168.102.31:3306/test  
  5.       username: root  
  6.       password: 123456  
  7.       driver-class-name: com.mysql.jdbc.Driver  
  8.     slave1:  
  9.       jdbc-url: jdbc:mysql://192.168.102.56:3306/test  
  10.       username: pig   # 只讀賬戶(hù)  
  11.       password: 123456  
  12.       driver-class-name: com.mysql.jdbc.Driver  
  13.     slave2:  
  14.       jdbc-url: jdbc:mysql://192.168.102.36:3306/test  
  15.       username: pig   # 只讀賬戶(hù)  
  16.       password: 123456  
  17.       driver-class-name: com.mysql.jdbc.Driver 

多數(shù)據(jù)源配置 

  1. package com.cjs.example.config;  
  2. import com.cjs.example.bean.MyRoutingDataSource;  
  3. import com.cjs.example.enums.DBTypeEnum;  
  4. import org.springframework.beans.factory.annotation.Qualifier;  
  5. import org.springframework.boot.context.properties.ConfigurationProperties;  
  6. import org.springframework.boot.jdbc.DataSourceBuilder;  
  7. import org.springframework.context.annotation.Bean;  
  8. import org.springframework.context.annotation.Configuration;  
  9. import javax.sql.DataSource;  
  10. import java.util.HashMap;  
  11. import java.util.Map;  
  12. /**  
  13.  * 關(guān)于數(shù)據(jù)源配置,參考SpringBoot官方文檔第79章《Data Access》  
  14.  * 79. Data Access  
  15.  * 79.1 Configure a Custom DataSource  
  16.  * 79.2 Configure Two DataSources  
  17.  */  
  18. @Configuration  
  19. public class DataSourceConfig {  
  20.     @Bean  
  21.     @ConfigurationProperties("spring.datasource.master")  
  22.     public DataSource masterDataSource() {  
  23.         return DataSourceBuilder.create().build();  
  24.     }  
  25.     @Bean  
  26.     @ConfigurationProperties("spring.datasource.slave1")  
  27.     public DataSource slave1DataSource() {  
  28.         return DataSourceBuilder.create().build();  
  29.     }  
  30.     @Bean  
  31.     @ConfigurationProperties("spring.datasource.slave2")  
  32.     public DataSource slave2DataSource() {  
  33.         return DataSourceBuilder.create().build();  
  34.     }  
  35.     @Bean  
  36.     public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,  
  37.                                           @Qualifier("slave1DataSource") DataSource slave1DataSource,  
  38.                                           @Qualifier("slave2DataSource") DataSource slave2DataSource) {  
  39.         Map<Object, Object> targetDataSources = new HashMap<>();  
  40.         targetDataSources.put(DBTypeEnum.MASTER, masterDataSource);  
  41.         targetDataSources.put(DBTypeEnum.SLAVE1, slave1DataSource);  
  42.         targetDataSources.put(DBTypeEnum.SLAVE2, slave2DataSource);  
  43.         MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();  
  44.         myRoutingDataSource.setDefaultTargetDataSource(masterDataSource);  
  45.         myRoutingDataSource.setTargetDataSources(targetDataSources);  
  46.         return myRoutingDataSource;  
  47.     }  

這里,我們配置了4個(gè)數(shù)據(jù)源,1個(gè)master,2兩個(gè)slave,1個(gè)路由數(shù)據(jù)源。前3個(gè)數(shù)據(jù)源都是為了生成第4個(gè)數(shù)據(jù)源,而且后續(xù)我們只用這最后一個(gè)路由數(shù)據(jù)源。

Spring Boot 最新基礎(chǔ)教程和示例源碼:https://github.com/javastacks/spring-boot-best-practice

MyBatis配置 

  1. package com.cjs.example.config;  
  2. import org.apache.ibatis.session.SqlSessionFactory;  
  3. import org.mybatis.spring.SqlSessionFactoryBean;  
  4. import org.springframework.context.annotation.Bean;  
  5. import org.springframework.context.annotation.Configuration;  
  6. import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 
  7. import org.springframework.jdbc.datasource.DataSourceTransactionManager;  
  8. import org.springframework.transaction.PlatformTransactionManager;  
  9. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  10. import javax.annotation.Resource;  
  11. import javax.sql.DataSource;  
  12. @EnableTransactionManagement  
  13. @Configuration  
  14. public class MyBatisConfig {  
  15.     @Resource(name = "myRoutingDataSource" 
  16.     private DataSource myRoutingDataSource;  
  17.     @Bean  
  18.     public SqlSessionFactory sqlSessionFactory() throws Exception {  
  19.         SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();  
  20.         sqlSessionFactoryBean.setDataSource(myRoutingDataSource);  
  21.         sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));  
  22.         return sqlSessionFactoryBean.getObject();  
  23.     }  
  24.     @Bean  
  25.     public PlatformTransactionManager platformTransactionManager() {  
  26.         return new DataSourceTransactionManager(myRoutingDataSource);  
  27.     }  

由于Spring容器中現(xiàn)在有4個(gè)數(shù)據(jù)源,所以我們需要為事務(wù)管理器和MyBatis手動(dòng)指定一個(gè)明確的數(shù)據(jù)源。另外,Spring 系列面試題和答案全部整理好了,微信搜索Java技術(shù)棧,在后臺(tái)發(fā)送:面試,可以在線(xiàn)閱讀。

3.3. 設(shè)置路由key / 查找數(shù)據(jù)源

目標(biāo)數(shù)據(jù)源就是那前3個(gè)這個(gè)我們是知道的,但是使用的時(shí)候是如果查找數(shù)據(jù)源的呢?

首先,我們定義一個(gè)枚舉來(lái)代表這三個(gè)數(shù)據(jù)源 

  1. package com.cjs.example.enums;  
  2. public enum DBTypeEnum {  
  3.     MASTER, SLAVE1, SLAVE2;  

接下來(lái),通過(guò)ThreadLocal將數(shù)據(jù)源設(shè)置到每個(gè)線(xiàn)程上下文中 

  1. package com.cjs.example.bean;  
  2. import com.cjs.example.enums.DBTypeEnum;  
  3. import java.util.concurrent.atomic.AtomicInteger; 
  4. public class DBContextHolder {  
  5.     private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();  
  6.     private static final AtomicInteger counter = new AtomicInteger(-1);  
  7.     public static void set(DBTypeEnum dbType) {  
  8.         contextHolder.set(dbType);  
  9.     } 
  10.     public static DBTypeEnum get() {  
  11.         return contextHolder.get();  
  12.     }  
  13.     public static void master() {  
  14.         set(DBTypeEnum.MASTER);  
  15.         System.out.println("切換到master");  
  16.     }  
  17.     public static void slave() { 
  18.         //  輪詢(xún)  
  19.         int index = counter.getAndIncrement() % 2;  
  20.         if (counter.get() > 9999) {  
  21.             counter.set(-1);  
  22.         }  
  23.         if (index == 0) {  
  24.             set(DBTypeEnum.SLAVE1);  
  25.             System.out.println("切換到slave1");  
  26.         }else {  
  27.             set(DBTypeEnum.SLAVE2);  
  28.             System.out.println("切換到slave2");  
  29.         }  
  30.     }  

獲取路由key 

  1. package com.cjs.example.bean;  
  2. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
  3. import org.springframework.lang.Nullable;  
  4. public class MyRoutingDataSource extends AbstractRoutingDataSource {  
  5.     @Nullable  
  6.     @Override  
  7.     protected Object determineCurrentLookupKey() {  
  8.         return DBContextHolder.get();  
  9.     }  

設(shè)置路由key

默認(rèn)情況下,所有的查詢(xún)都走從庫(kù),插入/修改/刪除走主庫(kù)。我們通過(guò)方法名來(lái)區(qū)分操作類(lèi)型(CRUD) 

  1. package com.cjs.example.aop;  
  2. import com.cjs.example.bean.DBContextHolder;  
  3. import org.apache.commons.lang3.StringUtils;  
  4. import org.aspectj.lang.JoinPoint; 
  5. import org.aspectj.lang.annotation.Aspect;  
  6. import org.aspectj.lang.annotation.Before;  
  7. import org.aspectj.lang.annotation.Pointcut;  
  8. import org.springframework.stereotype.Component;  
  9. @Aspect  
  10. @Component  
  11. public class DataSourceAop {  
  12.     @Pointcut("!@annotation(com.cjs.example.annotation.Master) " +  
  13.             "&& (execution(* com.cjs.example.service..*.select*(..)) " +  
  14.             "|| execution(* com.cjs.example.service..*.get*(..)))")  
  15.     public void readPointcut() {  
  16.     }  
  17.     @Pointcut("@annotation(com.cjs.example.annotation.Master) " +  
  18.             "|| execution(* com.cjs.example.service..*.insert*(..)) " +  
  19.             "|| execution(* com.cjs.example.service..*.add*(..)) " +  
  20.             "|| execution(* com.cjs.example.service..*.update*(..)) " + 
  21.             "|| execution(* com.cjs.example.service..*.edit*(..)) " +  
  22.             "|| execution(* com.cjs.example.service..*.delete*(..)) " +  
  23.             "|| execution(* com.cjs.example.service..*.remove*(..))")  
  24.     public void writePointcut() {  
  25.     }  
  26.     @Before("readPointcut()")  
  27.     public void read() {  
  28.         DBContextHolder.slave();  
  29.     }  
  30.     @Before("writePointcut()")  
  31.     public void write() {  
  32.         DBContextHolder.master();  
  33.     }  
  34.     /**  
  35.      * 另一種寫(xiě)法:if...else...  判斷哪些需要讀從數(shù)據(jù)庫(kù),其余的走主數(shù)據(jù)庫(kù)  
  36.      */  
  37. //    @Before("execution(* com.cjs.example.service.impl.*.*(..))")  
  38. //    public void before(JoinPoint jp) {  
  39. //        String methodName = jp.getSignature().getName();  
  40. //  
  41. //        if (StringUtils.startsWithAny(methodName, "get", "select", "find")) {  
  42. //            DBContextHolder.slave();  
  43. //        }else {  
  44. //            DBContextHolder.master();  
  45. //        }  
  46. //    }  

有一般情況就有特殊情況,特殊情況是某些情況下我們需要強(qiáng)制讀主庫(kù),針對(duì)這種情況,我們定義一個(gè)主鍵,用該注解標(biāo)注的就讀主庫(kù) 

  1. package com.cjs.example.annotation;  
  2. public @interface Master { 

例如,假設(shè)我們有一張表member 

  1. package com.cjs.example.service.impl;  
  2. import com.cjs.example.annotation.Master;  
  3. import com.cjs.example.entity.Member;  
  4. import com.cjs.example.entity.MemberExample;  
  5. import com.cjs.example.mapper.MemberMapper;  
  6. import com.cjs.example.service.MemberService;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.stereotype.Service;  
  9. import org.springframework.transaction.annotation.Transactional;  
  10. import java.util.List;  
  11. @Service  
  12. public class MemberServiceImpl implements MemberService { 
  13.     @Autowired  
  14.     private MemberMapper memberMapper;  
  15.     @Transactional  
  16.     @Override  
  17.     public int insert(Member member) {  
  18.         return memberMapper.insert(member);  
  19.     } 
  20.     @Master  
  21.     @Override  
  22.     public int save(Member member) {  
  23.         return memberMapper.insert(member);  
  24.     }  
  25.     @Override 
  26.     public List<Member> selectAll() {  
  27.         return memberMapper.selectByExample(new MemberExample());  
  28.     }  
  29.     @Master  
  30.     @Override  
  31.     public String getToken(String appId) {  
  32.         //  有些讀操作必須讀主數(shù)據(jù)庫(kù)  
  33.         //  比如,獲取微信access_token,因?yàn)楦叻鍟r(shí)期主從同步可能延遲  
  34.         //  這種情況下就必須強(qiáng)制從主數(shù)據(jù)讀  
  35.         return null;  
  36.     }  

4、測(cè)試 

  1. package com.cjs.example;  
  2. import com.cjs.example.entity.Member;  
  3. import com.cjs.example.service.MemberService;  
  4. import org.junit.Test;  
  5. import org.junit.runner.RunWith;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.boot.test.context.SpringBootTest;  
  8. import org.springframework.test.context.junit4.SpringRunner;  
  9. @RunWith(SpringRunner.class)  
  10. @SpringBootTest  
  11. public class CjsDatasourceDemoApplicationTests {  
  12.     @Autowired  
  13.     private MemberService memberService;  
  14.     @Test  
  15.     public void testWrite() {  
  16.         Member member = new Member();  
  17.         member.setName("zhangsan");  
  18.         memberService.insert(member);  
  19.     }  
  20.     @Test  
  21.     public void testRead() {  
  22.         for (int i = 0; i < 4; i++) {  
  23.             memberService.selectAll();  
  24.         }  
  25.     }  
  26.     @Test  
  27.     public void testSave() {  
  28.         Member member = new Member();  
  29.         member.setName("wangwu");  
  30.         memberService.save(member);  
  31.     }  
  32.     @Test  
  33.     public void testReadFromMaster() {  
  34.         memberService.getToken("1234");  
  35.     }  

查看控制臺(tái)

5、工程結(jié)構(gòu)

 

 

責(zé)任編輯:龐桂玉 來(lái)源: Java技術(shù)棧
相關(guān)推薦

2009-05-04 09:13:52

PHPMySQL讀寫(xiě)分離

2017-09-04 09:53:58

MySQLAtlasNavicat

2021-06-25 10:05:58

SpringBootMySQL數(shù)據(jù)庫(kù)

2017-05-25 10:22:13

NoSQL數(shù)據(jù)庫(kù)主主備份

2011-08-30 09:59:47

Mysql ProxyLUA

2020-11-24 09:56:12

數(shù)據(jù)源讀寫(xiě)分離

2020-04-23 15:08:41

SpringBootMyCatJava

2010-05-17 11:19:44

MySQL proxy

2020-03-24 14:16:18

ProxySQLMySQL數(shù)據(jù)庫(kù)

2022-04-25 08:03:57

MySQL中間件MyCat

2020-12-08 06:17:11

MycatMySQL分離

2011-08-30 12:49:59

Mysql ProxyLua分離

2024-01-22 08:46:37

MyBatis數(shù)據(jù)脫敏Spring

2023-12-13 12:20:36

SpringMySQL數(shù)據(jù)源

2024-01-16 08:17:29

Mybatis驗(yàn)證業(yè)務(wù)

2021-01-05 05:36:39

設(shè)計(jì)Spring Boot填充

2019-05-13 15:00:14

MySQLMyCat數(shù)據(jù)庫(kù)

2025-01-24 08:38:47

2019-09-30 09:19:54

Redis分離云數(shù)據(jù)庫(kù)

2024-07-31 09:56:20

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 国产精品久久久久久久久婷婷 | av毛片| 美女久久久久 | 日韩av一区二区在线观看 | 国产一区久久精品 | 免费观看的av | 最近中文字幕免费 | 午夜视频在线观看视频 | 男人av网 | 日韩在线观看中文字幕 | 亚州激情| 精精国产xxxx视频在线播放 | 久久精彩视频 | 影视先锋av资源噜噜 | dy天堂| 欧美日韩精选 | 男女视频在线观看免费 | 国产成人福利在线观看 | 亚洲顶级毛片 | 毛片免费视频 | 天天干免费视频 | 免费视频一区 | 伊人免费视频二 | 欧美高清成人 | 欧美一区不卡 | 亚洲一区二区久久 | 亚洲第一成年免费网站 | 亚洲一区二区在线视频 | 亚洲成人三级 | 亚洲三区在线观看 | 国产一级淫片免费视频 | 国产激情视频 | 日本久久精品视频 | 国产精品国产三级国产aⅴ无密码 | 中文字幕精品一区 | 国产一区欧美 | 国产精品福利视频 | 国产成人99久久亚洲综合精品 | 欧美日韩亚洲国产 | 特黄视频 | 国产一级片一区二区三区 |