啟動原始碼詳解
- 通過上面的二篇文章,我相信您對tcc應該有個大體的瞭解,並且已經搭建好了除錯環境,那麼就讓我們一起探索tcc的原始碼之旅。
- 首先看任何框架的原始碼都需要找到框架的入口,tcc也不例外,還記得我們在專案中applicationContext.xml有一段這麼的配置嗎?
<!-- Aspect 切面配置,是否開啟AOP切面--> <aop:aspectj-autoproxy expose-proxy="true"/> <!--掃描框架的包--> <context:component-scan base-package="com.happylifeplat.tcc.*"/> <!--啟動類屬性配置--> <bean id="tccTransactionBootstrap" class="com.happylifeplat.tcc.core.bootstrap.TccTransactionBootstrap"> <property name="serializer" value="kryo"/> <property name="coordinatorQueueMax" value="5000"/> <property name="coordinatorThreadMax" value="4"/> <property name="recoverDelayTime" value="120"/> <property name="retryMax" value="3"/> <property name="rejectPolicy" value="Abort"/> <property name="blockingQueueType" value="Linked"/> <property name="scheduledDelay" value="120"/> <property name="scheduledThreadMax" value="4"/> <property name="repositorySupport" value="db"/> <property name="tccDbConfig"> <bean class="com.happylifeplat.tcc.common.config.TccDbConfig"> <property name="url" value="jdbc:mysql://192.168.1.68:3306/account?useUnicode=true&characterEncoding=utf8"/> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="password" value="Wgj@555888"/> <property name="username" value="xiaoyu"/> </bean> </property> </bean>複製程式碼
- 通過以上的配置我們知道首先需要開啟Aop切面,再掃描框架的包,重點我們來關注 TccTransactionBootstrap
TccTransactionBootstrap 原始碼解析
package com.happylifeplat.tcc.core.bootstrap;
import com.happylifeplat.tcc.common.config.TccConfig;
import com.happylifeplat.tcc.core.helper.SpringBeanUtils;
import com.happylifeplat.tcc.core.service.TccInitService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class TccTransactionBootstrap extends TccConfig implements ApplicationContextAware {
private final TccInitService tccInitService;
@Autowired
public TccTransactionBootstrap(TccInitService tccInitService) {
this.tccInitService = tccInitService;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//儲存spring的上下文
SpringBeanUtils.getInstance().setCfgContext((ConfigurableApplicationContext) applicationContext);
start(this);
}
private void start(TccConfig tccConfig) {
tccInitService.initialization(tccConfig);
}
}複製程式碼
它繼承 TccConfig 能獲取在xml配置的屬性資訊,實現 ApplicationContextAware 當spring容器初始化的時候,會自動的將ApplicationContext注入進來
我們繼續跟蹤程式碼,進入initialization 方法
public void initialization(TccConfig tccConfig) { Runtime.getRuntime().addShutdownHook(new Thread(() -> LOGGER.error("系統關閉"))); try { //載入spi配置,把spi的配置注入成spring的bean 方便後續的使用 //就是框架所支援的序列化,儲存方式 LoadSpiSupport(tccConfig); coordinatorService.start(tccConfig); } catch (Exception ex) { LogUtil.error(LOGGER, "tcc事務初始化異常:{}", ex::getMessage); System.exit(1);//非正常關閉 } LogUtil.info(LOGGER, () -> "Tcc事務初始化成功!"); }複製程式碼
LoadSpiSupport 採用jdk自帶的spi載入,如果有不明白的小夥伴,可以自行google
我們繼續進入 coordinatorService.start(tccConfig)
@Override public void start(TccConfig tccConfig) throws Exception { this.tccConfig = tccConfig; //獲取應用名稱 final String appName = applicationService.acquireName(); //獲取上一步載入的spi資源資訊 coordinatorRepository = SpringBeanUtils.getInstance().getBean(CoordinatorRepository.class); //初始化spi 協調資源儲存 coordinatorRepository.init(appName, tccConfig); //初始化 協調資源執行緒池 initCoordinatorPool(); //定時執行補償 scheduledRollBack(); }複製程式碼
coordinatorRepository.init(appName, tccConfig) 就是根據spi思想來具體初始化,現在支援的如圖:
initCoordinatorPool() 初始化 協調資源執行緒池
private void initCoordinatorPool() { synchronized (LOGGER) { //採用LinkedBlockingQueue QUEUE = new LinkedBlockingQueue<>(tccConfig.getCoordinatorQueueMax()); final int coordinatorThreadMax = tccConfig.getCoordinatorThreadMax(); final TccTransactionThreadPool threadPool = SpringBeanUtils.getInstance().getBean(TccTransactionThreadPool.class); //獲取固定數量執行緒大小的執行緒池 final ExecutorService executorService = threadPool.newCustomFixedThreadPool(coordinatorThreadMax); LogUtil.info(LOGGER, "啟動協調資源操作執行緒數量為:{}", () -> coordinatorThreadMax); for (int i = 0; i < coordinatorThreadMax; i++) { //執行執行緒 executorService.execute(new Worker()); } } } class Worker implements Runnable { @Override public void run() { execute(); } private void execute() { while (true) { try { //阻塞佇列獲取 final CoordinatorAction coordinatorAction = QUEUE.take(); if (coordinatorAction != null) { final int code = coordinatorAction.getAction().getCode(); if (CoordinatorActionEnum.SAVE.getCode() == code) { save(coordinatorAction.getTccTransaction()); } else if (CoordinatorActionEnum.DELETE.getCode() == code) { remove(coordinatorAction.getTccTransaction().getTransId()); } else if (CoordinatorActionEnum.UPDATE.getCode() == code) { update(coordinatorAction.getTccTransaction()); } } } catch (Exception e) { e.printStackTrace(); LogUtil.error(LOGGER, "執行協調命令失敗:{}", e::getMessage); } } } }複製程式碼
scheduledRollBack() 執行定時補償,這個以後再詳細講解邏輯