做者:狂乱的贵令郎
链接:https://www.cnblogs.com/cjsblog/p/9712457.html
1、引言读写别离要做的工作就是关于一条SQL该选择哪个数据库去施行,至于谁来做选择数据库那件事儿,无非两个,要么中间件帮我们做,要么法式本身做。
因而,一般来讲,读写别离有两种实现体例。第一种是依靠中间件(好比:MyCat),也就是说应用法式毗连到中间件,中间件帮我们做SQL别离;第二种是应用法式本身去做别离。那里我们选择法式本身来做,次要是操纵Spring供给的路由数据源,以及AOP
然而,应用法式层面去做读写别离更大的弱点(不敷之处)在于无法动态增加数据库节点,因为数据源设置装备摆设都是写在设置装备摆设中的,新增数据库意味着新加一个数据源,一定改设置装备摆设,并重启应用。当然,益处就是相对简单。
2、AbstractRoutingDataSource基于特定的查找key路由到特定的数据源。它内部维护了一组目的数据源,而且做了路由key与目的数据源之间的映射,供给基于key查找数据源的办法。
3、理论3.1. maven依赖"1.0" encoding="UTF-8"?>"http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.cjs.example cjs-datasource-demo 0.0.1-SNAPSHOT jar cjs-datasource-demo org.springframework.boot spring-boot-starter-parent 2.0.5.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-aop org.springframework.boot spring-boot-starter-jdbc org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 org.apache.commons commons-lang3 3.8 mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin 3.2. 数据源设置装备摆设application.yml
spring: datasource: master: jdbc-url: jdbc:mysql://192.168.102.31:3306/test username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver slave1: jdbc-url: jdbc:mysql://192.168.102.56:3306/test username: pig # 只读账户 password: 123456 driver-class-name: com.mysql.jdbc.Driver slave2: jdbc-url: jdbc:mysql://192.168.102.36:3306/test username: pig # 只读账户 password: 123456 driver-class-name: com.mysql.jdbc.Driver大都据源设置装备摆设
package com.cjs.example.config;import com.cjs.example.bean.MyRoutingDataSource;import com.cjs.example.enums.DBTypeEnum;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.jdbc.DataSourceBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;import java.util.HashMap;import java.util.Map;@Configurationpublic class DataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.master") public DataSource masterDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.slave1") public DataSource slave1DataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.slave2") public DataSource slave2DataSource() { return DataSourceBuilder.create().build(); } @Bean public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slave1DataSource") DataSource slave1DataSource, @Qualifier("slave2DataSource") DataSource slave2DataSource) { Map targetDataSources = new HashMap<>(); targetDataSources.put(DBTypeEnum.MASTER, masterDataSource); targetDataSources.put(DBTypeEnum.SLAVE1, slave1DataSource); targetDataSources.put(DBTypeEnum.SLAVE2, slave2DataSource); MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource(); myRoutingDataSource.setDefaultTargetDataSource(masterDataSource); myRoutingDataSource.setTargetDataSources(targetDataSources); return myRoutingDataSource; }}那里,我们设置装备摆设了4个数据源,1个master,2两个slave,1个路由数据源。前3个数据源都是为了生成第4个数据源,并且后续我们只用那最初一个路由数据源。
MyBatis设置装备摆设
package com.cjs.example.config;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.PlatformTransactionManager;import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.annotation.Resource;import javax.sql.DataSource;@EnableTransactionManagement@Configurationpublic class MyBatisConfig { @Resource(name = "myRoutingDataSource") private DataSource myRoutingDataSource; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(myRoutingDataSource); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper// @Before("execution(* com.cjs.example.service.impl.*.*(..))")// public void before(JoinPoint jp) {// String methodName = jp.getSignature().getName();//// if (StringUtils.startsWithAny(methodName, "get", "select", "find")) {// DBContextHolder.slave();// }else {// DBContextHolder.master();// }// }}有一般情况就有特殊情况,特殊情况是某些情况下我们需要强迫读主库,针对那种情况,我们定义一个主键,用该注解标注的就读主库
package com.cjs.example.annotation;public @interface Master {}例如,假设我们有一张表member
package com.cjs.example.service.impl;import com.cjs.example.annotation.Master;import com.cjs.example.entity.Member;import com.cjs.example.entity.MemberExample;import com.cjs.example.mapper.MemberMapper;import com.cjs.example.service.MemberService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.List;@Servicepublic class MemberServiceImpl implements MemberService { @Autowired private MemberMapper memberMapper; @Transactional @Override public int insert(Member member) { return memberMapper.insert(member); } @Master @Override public int save(Member member) { return memberMapper.insert(member); } @Override public List selectAll() { return memberMapper.selectByExample(new MemberExample()); } @Master @Override public String getToken(String appId) { // 有些读操做必需读主数据库 // 好比,获取微信access_token,因为顶峰期间主从同步可能延迟 // 那种情况下就必需强迫从主数据读 return null; }}4、测试package com.cjs.example;import com.cjs.example.entity.Member;import com.cjs.example.service.MemberService;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)@SpringBootTestpublic class CjsDatasourceDemoApplicationTests { @Autowired private MemberService memberService; @Test public void testWrite() { Member member = new Member(); member.setName("zhangsan"); memberService.insert(member); } @Test public void testRead() { for (int i = 0; i < 4; i++) { memberService.selectAll(); } } @Test public void testSave() { Member member = new Member(); member.setName("wangwu"); memberService.save(member); } @Test public void testReadFromMaster() { memberService.getToken("1234"); }}查看控造台


5、工程构造
参考:
https://www.jianshu.com/p/f2f4256a2310http://www.cnblogs.com/gl-developer/p/6170423.htmlhttps://www.cnblogs.com/huangjuncong/p/8576935.htmlhttps://blog.csdn.net/liu976180578/article/details/77684583
--- EOF ---保举↓↓↓





还没有评论,来说两句吧...