前言:目前在接手學校的一個專案,架構是SSM,用到了讀寫分離,學弟改成把專案改成了SpringBoot,因為流量不大,所以取消了讀寫分離,為了確保專案的沒問題,同時多學點知識,決定先復盤一下之前SSM專案的讀寫分離,然后學習一下在SpringBoot中如何實作讀寫分離,這里出于循序漸進的考慮,在這篇文章中我們先實作在SpringBoot+Mybatis架構下動態的切換資料源,后面的文章再實作讀寫分離,
參考:
https://www.cnblogs.com/panxuejun/p/6770515.html
https://blog.csdn.net/qq_37502106/article/details/91044952
目錄
第一章 SSM專案中的讀寫分離(僅講解)
1.1 DataSource
1.2 組態檔
1.3 實作機制分析
第二章 SpringBoot+mybatis實作動態切換資料源
2.1 組態檔
2.2 多資料源的配置代碼
2.3 基礎公用代碼
2.4 測驗代碼
第一章 SSM專案中的讀寫分離(僅講解)
1.1 DataSource
DataSource是一個介面,可以獲取資料庫的Connection,
為什么要設定DataSource呢,個人是這么理解的,業務不應該被資料庫的型別所干擾,所以設定一個DataSource介面,有需要連接直接呼叫介面,有需要更換資料庫也不需要改業務,改一下DataSource的實作就好了,
DataSource有不同的實作方案,如c3p0連接池或者阿里的DruidDataSource連接池,
值得注意的是,如果要某些現成框架操作資料庫,僅僅實作了DataSource介面還是不夠的,我們還需要將DataSource注入到我們操作資料庫的工具中,如JdbcTemplate或者Mybatis,個人理解的話就是,DataSource負責獲取連接,資料庫框架負責用這些連接進行查詢,
1.2 組態檔
先來看一下老專案中讀寫分離的組態檔,這里對一些涉及到隱私的更換了點資訊
資料庫組態檔(jdbc.properties):
#write主庫(讀寫)
write.jdbc.driver=com.mysql.jdbc.Driver
write.jdbc.url=jdbc:mysql://127.0.0.1:3306/yjpj?useUnicode=true&characterEncoding=utf8&useSSL=false
write.jdbc.username=writeuser
write.jdbc.password=123456
read.jdbc.driver=com.mysql.jdbc.Driver
read.jdbc.url=jdbc:mysql://127.0.0.1:3306/yjpj?useUnicode=true&characterEncoding=utf8&useSSL=false
read.jdbc.username=writeuser
read.jdbc.password=123456
################################連接池配置###################################################
#druid連接池配置相關
#初始化連接池連接數大小
druid.initialSize=20
#連接池最小空閑連接數
druid.minIdle=20
#連接池最大連接數
druid.maxActive=100
#配置獲取連接等待超時的時間(單位:毫秒)
druid.maxWait=60000
#配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
druid.timeBetweenEvictionRunsMillis=60000
#配置一個連接在池中最小生存的時間,單位是毫秒
druid.minEvictableIdleTimeMillis=40000
Mybatis組態檔(spring-dao.xml):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<context:annotation-config/>
<!-- 1.配置資料庫相關引數properties的屬性:${url} -->
<context:property-placeholder location="classpath:*.properties" />
<!-- 2.1.兩個資料源公共部分 -->
<!-- druid資料庫連接池 -->
<bean id="abstractDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${druid.initialSize}" />
<property name="minIdle" value="${druid.minIdle}" />
<property name="maxActive" value="${druid.maxActive}" />
<!-- 配置獲取連接等待超時的時間(單位:毫秒) -->
<property name="maxWait" value="${druid.maxWait}" />
<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
<!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="select 'x'" />
<property name="testWhileIdle" value="true" />
<!-- 配置監控統計攔截的filters,去掉后監控界面sql無法統計 -->
<property name="filters" value="stat" />
</bean>
<!-- 2.2.寫庫資料源 -->
<bean id="writeDataSource" parent="abstractDataSource">
<!-- 配置連接池屬性 -->
<property name="driverClassName" value="${write.jdbc.driver}" />
<property name="url" value="${write.jdbc.url}" />
<property name="username" value="${write.jdbc.username}" />
<property name="password" value="${write.jdbc.password}" />
</bean>
<!-- 2.3.讀庫資料源 -->
<bean id="readDataSource" parent="abstractDataSource">
<!-- 配置連接池屬性 -->
<property name="driverClassName" value="${read.jdbc.driver}" />
<property name="url" value="${read.jdbc.url}" />
<property name="username" value="${read.jdbc.username}" />
<property name="password" value="${read.jdbc.password}" />
</bean>
<!-- 3.配置動態資料源 -->
<bean id="dataSource" class="com.qcpj.common.db.DynamicDataSource">
<property name="targetDataSources">
<map>
<entry key="write" value-ref="writeDataSource" />
<entry key="read" value-ref="readDataSource" />
</map>
</property>
<!-- 默認使用主庫 -->
<property name="defaultTargetDataSource" ref="writeDataSource" />
</bean>
<!-- 4.配置SqlSessionFactory物件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入資料庫連接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBaties全域組態檔:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 掃描sql組態檔:mapper需要的xml檔案 -->
<property name="mapperLocations" value="classpath:mapper/**/*.xml" />
</bean>
<!-- 5.配置掃描Dao介面包,動態實作Dao介面,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!-- 給出需要掃描Dao介面包 -->
<property name="basePackage" value="com.qcpj.**.dao" />
</bean>
</beans>
運行代碼:
public class DS {
private static Logger logger = LoggerFactory.getLogger(DS.class);
@Autowired
private static DataSourceHolder dsh;
//切換為寫資料庫
public static void write() {
logger.debug("DataSource : write");
dsh.setWrite();
}
//切換為讀資料庫
public static void read() {
logger.debug("DataSource : read");
dsh.setRead();
}
}
public class DataSourceHolder {
// 執行緒本地環境
private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();
// 設定資料源
public static void setDataSource(String customerType) {
dataSources.set(customerType);
}
// 設定資料源為寫庫
public static void setWrite() {
dataSources.remove();
}
// 設定資料庫為讀庫
public static void setRead() {
dataSources.set("read");
}
// 獲取資料源
public static String getDataSource() {
return (String) dataSources.get();
}
// 清除資料源
public static void clearDataSource() {
dataSources.remove();
}
}
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceHolder.getDataSource();
}
}
1.3 實作機制分析
這里因為SSM再配置有點麻煩就不配置了,主要是講解一下思路,后面會用SpringBoot實作讀寫分離,
可以看到使用DruidDataSource創建了兩個資料源,一個是讀資料源readDataSource,一個是寫資料源writeDataSource,
將兩個資料源注入了DynamicDataSource中(讀和寫注入了targetDataSources中,其中也設定了默認資料源defaultTargetDataSource),可以看到而DynamicDataSource繼承了AbstractRoutingDataSource,其實也就是注入了AbstractRoutingDataSource中,在網上查到,動態切換資料資料源只要實作AbstractRoutingDataSource中的determineCurrentLookupKey方法,個人推測的話,AbstractRoutingDataSource會根據determineCurrentLookupKey方法回傳的值去targetDataSources中查找對應的資料源,查找到對應的資料源后就會進行對應的切換,如果找不到的話就會回傳默認,
我們的tomcat在處理請求時會使用執行緒池,所以這里我們有必要建立一個單例的ThreadLocal,來確保資料源的切換不會因為多執行緒而干擾運行,如果不設立,則會發生如一個執行緒切換為讀模式,另一個執行緒切換為寫模式,然后就都按寫模式來了,這屬于多執行緒操作共享資源吧,好象加鎖也行,不過那就太慢了,所以我們上面建立了一個單例的dataSources,為每個執行緒建立獨特的資料,
下面是一個資料源切換的實際代碼,這里本人思考了一下,我認為其實表面說是資料源切換,實際上是根據key回傳對應資料源的連接,如果資料源是切換的,那一個執行緒切換為寫,一個切換為讀那就沖突了,所以實際就是當執行sql需要連接時,呼叫對應的函式獲取資料源的key,然后去map中拿到對應的資料源連接進行使用(僅僅是個人推斷,沒看原始碼)
//讀的應用
DS.read();
List<EvaluationTemplateDto> list = evaluationTemplateDao.query(schoolId, grade, type,
subject, target);
//寫的應用
DS.write();
List<EvaluationHabitDto> evaluationHabits = new ArrayList<EvaluationHabitDto>();
for (TeacherEvaluation evaluation : teacherEvaluations) {
//自定義評價不進行記錄
if(evaluation.getContentId().equals("-1") == false) {
EvaluationHabitDto evaluationHabit = new EvaluationHabitDto();
evaluationHabit.setSubject(evaluation.getSubject());
evaluationHabit.setTeacherId(evaluation.getTeacherId());
evaluationHabit.setTemplateId(evaluation.getContentId());
evaluationHabits.add(evaluationHabit);
}
}
第二章 SpringBoot+mybatis實作動態切換資料源
這里主要是列代碼了,具體的決議在看了第一章應該是沒問題的,大致的專案架構如下:

2.1 組態檔
maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
application.properties:
server.port=8080
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 資料源1
spring.datasource.druid.first.url=jdbc:mysql://localhost:3306/mysql_learn?serverTimezone=GMT%2B8
spring.datasource.druid.first.username=root
spring.datasource.druid.first.password=123456
# 資料源2
spring.datasource.druid.second.url=jdbc:mysql://localhost:3306/mysql_learn_copy?serverTimezone=GMT%2B8
spring.datasource.druid.second.username=root
spring.datasource.druid.second.password=123456
mybatis.mapperLocations=classpath:mappers/*.xml
Person.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aesjourey.mybatisspringboot.dao.PersonMapper">
<select id="getPersonById" parameterType="String" resultType="com.aesjourey.mybatisspringboot.entity.Person">
select * from person where person_id = #{0}
</select>
</mapper>
2.2 多資料源的配置代碼
public interface DataSourceNames {
String FIRST ="first";
String SECOND = "second";
}
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return getDataSource();
}
public static void setDataSource(String dataSource) {
CONTEXT_HOLDER.set(dataSource);
}
public static String getDataSource() {
return CONTEXT_HOLDER.get();
}
public static void clearDataSource() {
CONTEXT_HOLDER.remove();
}
}
@Configuration
public class DynamicDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.first")
public DataSource firstDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.second")
public DataSource secondDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@Primary
public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>(5);
targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
return new DynamicDataSource(firstDataSource, targetDataSources);
}
}
這里有個特別重要的,要在啟動類注解上排除掉@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) ,因為springboot會自動注入datasource,會引起回圈依賴,至于為什么自動注入會引起回圈依賴我也不清楚,有知道的可以在評論區說一下,后面我會再研究下這個問題,參考的是這個文章的評論區:https://blog.csdn.net/weixin_34344677/article/details/85965061
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class})
@MapperScan("com.aesjourey.mybatisspringboot.dao")
public class MybatisspringbootApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisspringbootApplication.class, args);
}
}
回圈依賴大概就是下面的樣子:
The dependencies of some of the beans in the application context form a cycle:
getPerson (field com.aesjourey.mybatisspringboot.service.PersonService com.aesjourey.mybatisspringboot.controller.getPerson.personService)
↓
personService (field com.aesjourey.mybatisspringboot.dao.PersonMapper com.aesjourey.mybatisspringboot.service.PersonService.personMapper)
↓
personMapper defined in file [F:\IdeaProjects\mybatisspringboot\target\classes\com\aesjourey\mybatisspringboot\dao\PersonMapper.class]
↓
sqlSessionFactory defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]
┌─────┐
| dataSource defined in class path resource [com/aesjourey/mybatisspringboot/common/config/DynamicDataSourceConfig.class]
↑ ↓
| firstDataSource defined in class path resource [com/aesjourey/mybatisspringboot/common/config/DynamicDataSourceConfig.class]
↑ ↓
| org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker
└─────┘
2.3 基礎公用代碼
@Getter
@Setter
public class Person {
String person_id;
String name;
int age;
String school;
String home;
}
public interface PersonMapper {
Person getPersonById(String personId);
}
@Service
public class PersonService {
@Autowired
PersonMapper personMapper;
public Person getPersonById(String peopleId){
Person person = personMapper.getPersonById(peopleId);
return person;
}
}
2.4 測驗代碼
@RestController
public class getPerson {
static int i=0;
@Autowired
PersonService personService;
@RequestMapping("/getPersonByPersonId")
public Person getPersonByPersonId(String personId){
if(i++%2==0){
DynamicDataSource.setDataSource(DataSourceNames.FIRST);
}else{
DynamicDataSource.setDataSource(DataSourceNames.SECOND);
}
Person person = personService.getPersonById(personId);
System.out.println(Thread.currentThread());
return person;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/201673.html
標籤:其他
上一篇:集群&分布式&節點
