赞
踩
前几篇分享了seata客户端整个流程的源码,TM,RM相关,今天开始我们从细节入手,全面无死角分析seata源码,首先承接上一篇的内容,分析数据源代理是怎么生成的,并且通过业务演示此数据源。
一、启动时生成代理数据源:
1、SPI机制自动代理配置类入口:在seata-spring-boot-starter模块的SeataDataSourceAutoConfiguration 配置类中,开启了seata数据源的自动代理。
点击 SeataDataSourceAutoConfiguration 类进入
- @ConditionalOnBean(DataSource.class)//处理 DataSource 数据源的类
- //此处配置对应配置文件中的参数,比如nacos中的配置
- @ConditionalOnExpression("${seata.enable:true} && ${seata.enableAutoDataSourceProxy:true} && ${seata.enable-auto-data-source-proxy:true}")
- public class SeataDataSourceAutoConfiguration {
-
- /**
- * The bean seataDataSourceBeanPostProcessor.
- * 生成数据源的代理对象
- */
- @Bean(BEAN_NAME_SEATA_DATA_SOURCE_BEAN_POST_PROCESSOR)
- @ConditionalOnMissingBean(SeataDataSourceBeanPostProcessor.class)
- public SeataDataSourceBeanPostProcessor seataDataSourceBeanPostProcessor(SeataProperties seataProperties) {
- //点击进入
- return new SeataDataSourceBeanPostProcessor(seataProperties.getExcludesForAutoProxying(), seataProperties.getDataSourceProxyMode());
- }
-
- /**
- * The bean seataAutoDataSourceProxyCreator.
- * 在上面的类中,生成了数据源的代理对象,那么执行数据增删改查时,是如何切换到代理数据源的呢?
- * SeataAutoDataSourceProxyCreator继承了AbstractAutoProxyCreator抽象类,Spring
- * 通过 AbstractAutoProxyCreator来创建 AOP 代理,其实现了BeanPostProcessor 接口,用于在 bean 初始化完成之后创建它的代理。
- * 在Seata 中,该类目的是为数据源添加Advisor,当数据源执行操作时,会进入其 SeataAutoDataSourceProxyAdvice 类中处理,比如进入(GlobalTransactionalInterceptor的invoke方法)
- */
- @Bean(BEAN_NAME_SEATA_AUTO_DATA_SOURCE_PROXY_CREATOR)
- @ConditionalOnMissingBean(SeataAutoDataSourceProxyCreator.class)
- public SeataAutoDataSourceProxyCreator seataAutoDataSourceProxyCreator(SeataProperties seataProperties) {
- //点击进入
- return new SeataAutoDataSourceProxyCreator(seataProperties.isUseJdkProxy(),
- seataProperties.getExcludesForAutoProxying(), seataProperties.getDataSourceProxyMode());
- }
- }
注解里的配置对应配置文件里的:比如nacos中,截取部分配置如下
如果在java类中注解 就可以看看这个 SeataProperties 类,一目了然。
2、点击 SeataDataSourceBeanPostProcessor 进入
- public class SeataDataSourceBeanPostProcessor implements BeanPostProcessor {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(SeataDataSourceBeanPostProcessor.class);
-
- private final List<String> excludes;
- private final BranchType dataSourceProxyMode;
-
- //构造函数
- public SeataDataSourceBeanPostProcessor(String[] excludes, String dataSourceProxyMode) {
- this.excludes = Arrays.asList(excludes);
- this.dataSourceProxyMode = BranchType.XA.name().equalsIgnoreCase(dataSourceProxyMode) ? BranchType.XA : BranchType.AT;
- }
-
- @Override
- public Object postProcessBeforeInitialization(Object bean, String beanName) {
- return bean;
- }
-
- @Override//此类继承 BeanPostProcessor,此处是后置处理器方法,对象初始化后执行
- public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
- if (bean instanceof DataSource) {
- //When not in the excludes, put and init proxy.
- // 配置中没有忽略DataSource类的代理,则进行代理
- if (!excludes.contains(bean.getClass().getName())) {
- //Only put and init proxy, not return proxy. 初始化代理,进入 DataSourceProxyHolder
- DataSourceProxyHolder.get().putDataSource((DataSource) bean, dataSourceProxyMode);
- }
-
- //If is SeataDataSourceProxy, return the original data source.
- // 如果Bean 已经是SeataDataSourceProxy,返回原来的数据源
- if (bean instanceof SeataDataSourceProxy) {
- LOGGER.info("Unwrap the bean of the data source," +
- " and return the original data source to replace the data source proxy.");
- return ((SeataDataSourceProxy) bean).getTargetDataSource();
- }
- }
- return bean;
- }
- }
3、点击 DataSourceProxyHolder.get().putDataSource((DataSource) bean, dataSourceProxyMode);先 初始化DataSourceProxyHolder对象
初始化对象:
- // 初始化 DataSourceProxyHolder 对象
- public static DataSourceProxyHolder get() {
- return Holder.INSTANCE;
- }
生成创建代理:
- public SeataDataSourceProxy putDataSource(DataSource dataSource, BranchType dataSourceProxyMode) {
- DataSource originalDataSource;
- // 1. 如果数据源是SeataDataSourceProxy,则直接返回
- if (dataSource instanceof SeataDataSourceProxy) {
- SeataDataSourceProxy dataSourceProxy = (SeataDataSourceProxy) dataSource;
-
- //If it's an right proxy, return it directly.
- // 如果是正确的代理,请直接返回。
- if (dataSourceProxyMode == dataSourceProxy.getBranchType()) {
- return (SeataDataSourceProxy) dataSource;
- }
-
- //Get the original data source. 获取原始数据源。
- originalDataSource = dataSourceProxy.getTargetDataSource();
- } else {
- originalDataSource = dataSource;
- }
- // 2. 从存放代理的集合中获取该数据源的代理数据源
- SeataDataSourceProxy dsProxy = dataSourceProxyMap.get(originalDataSource);
- if (dsProxy == null) {
- // 3.如果没有则创建代理并放入集合中
- synchronized (dataSourceProxyMap) {
- dsProxy = dataSourceProxyMap.get(originalDataSource);
- if (dsProxy == null) {//获取代理数据源,点击进入
- dsProxy = createDsProxyByMode(dataSourceProxyMode, originalDataSource);
- dataSourceProxyMap.put(originalDataSource, dsProxy);
- }
- }
- }
- return dsProxy;//4. 返回
- }
点击 createDsProxyByMode 方法
-
- private SeataDataSourceProxy createDsProxyByMode(BranchType mode, DataSource originDs) {
- //如果是XA 模式,创建DataSourceProxyXA,其他模式(AT模式)创建DataSourceProxy
- //到此正式获取代理数据源,此后就可以执行RM数据库资源操作了
- return BranchType.XA == mode ? new DataSourceProxyXA(originDs) : new DataSourceProxy(originDs);
- }
4、然后回到最上游看 SeataAutoDataSourceProxyCreator 类,点击进入:
- public class SeataAutoDataSourceProxyCreator extends AbstractAutoProxyCreator {
- private static final Logger LOGGER = LoggerFactory.getLogger(SeataAutoDataSourceProxyCreator.class);
- private final List<String> excludes;
- private final Advisor advisor;
-
- public SeataAutoDataSourceProxyCreator(boolean useJdkProxy, String[] excludes, String dataSourceProxyMode) {
- this.excludes = Arrays.asList(excludes);
- /**
- * 当数据源执行操作时,由于添加了AOP代理,最终会进入到 SeataAutoDataSourceProxyAdvice 的invoke方法中,点击进入
- */
- this.advisor = new DefaultIntroductionAdvisor(new SeataAutoDataSourceProxyAdvice(dataSourceProxyMode));
- setProxyTargetClass(!useJdkProxy);
- }
-
- @Override// 为数据源Bean 添加 Advisor
- protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource customTargetSource) throws BeansException {
- if (LOGGER.isInfoEnabled()) {
- LOGGER.info("Auto proxy of [{}]", beanName);
- }
- return new Object[]{advisor};
- }
-
- @Override// 不是DataSource 则跳过
- protected boolean shouldSkip(Class<?> beanClass, String beanName) {
- return !DataSource.class.isAssignableFrom(beanClass) ||
- SeataProxy.class.isAssignableFrom(beanClass) ||
- excludes.contains(beanClass.getName());
- }
- }
5、点击SeataAutoDataSourceProxyAdvice
- public class SeataAutoDataSourceProxyAdvice implements MethodInterceptor, IntroductionInfo {
-
- private final BranchType dataSourceProxyMode;
- private final Class<? extends SeataDataSourceProxy> dataSourceProxyClazz;
-
- public SeataAutoDataSourceProxyAdvice(String dataSourceProxyMode) {
- if (BranchType.AT.name().equalsIgnoreCase(dataSourceProxyMode)) {
- this.dataSourceProxyMode = BranchType.AT;
- this.dataSourceProxyClazz = DataSourceProxy.class;
- } else if (BranchType.XA.name().equalsIgnoreCase(dataSourceProxyMode)) {
- this.dataSourceProxyMode = BranchType.XA;
- this.dataSourceProxyClazz = DataSourceProxyXA.class;
- } else {
- throw new IllegalArgumentException("Unknown dataSourceProxyMode: " + dataSourceProxyMode);
- }
-
- //Set the default branch type in the RootContext.
- RootContext.setDefaultBranchType(this.dataSourceProxyMode);
- }
-
- //代理调用进入的方法
- @Override
- public Object invoke(MethodInvocation invocation) throws Throwable {
- if (!RootContext.requireGlobalLock() && dataSourceProxyMode != RootContext.getBranchType()) {
- return invocation.proceed();
- }
- // 数据源执行的方法,比如获取连接的 getConnection()
- Method method = invocation.getMethod();
- Object[] args = invocation.getArguments();
- // 查询代理数据源对应的方法 DataSourceProxy.getConnection()
- Method m = BeanUtils.findDeclaredMethod(dataSourceProxyClazz, method.getName(), method.getParameterTypes());
- if (m != null && DataSource.class.isAssignableFrom(method.getDeclaringClass())) {//获取代理数据源
- SeataDataSourceProxy dataSourceProxy = DataSourceProxyHolder.get().putDataSource((DataSource) invocation.getThis(), dataSourceProxyMode);
- // 执行代理数据源的方法
- return m.invoke(dataSourceProxy, args);
- } else {
- return invocation.proceed();
- }
- }
-
- @Override
- public Class<?>[] getInterfaces() {
- return new Class[]{SeataProxy.class};
- }
-
- }
6、谁调用 getAdvicesAndAdvisorsForBean 方法,Ctrl + g 看到很熟悉的方法
来到
二、业务代码演示数据源执行流程:
首先需要明白,数据源或者代理数据源肯定是要放到JDBC里面的,单独的JDBC或者封装后的ORM框架(mybatis...),此处为了方便演示我们采用原生的JDBC,这样更容易看源码;
1、业务里配置代理数据源
- /**
- * seata的数据源代理
- */
- @Data
- @Configuration
- @ConfigurationProperties(prefix = "druid-master",ignoreInvalidFields = true)
- public class DataSourceConfiguration {
- //配置的数据源参数
- private String driverClassName;
- private String username;
- private String jdbcUrl;
- private String password;
- private int maxActive;
- private int minIdle;
- private int initialSize;
- private Long timeBetweenEvictionRunsMillis;
- private Long minEvictableIdleTimeMillis;
- private String validationQuery;
- private boolean testWhileIdle;
- private boolean testOnBorrow;
- private boolean testOnReturn;
- private boolean poolPreparedStatements;
- private Integer maxPoolPreparedStatementPerConnectionSize;
- private String filters;
- private String connectionProperties;
-
- //原始数据源配置
- @Bean(name = "masterDataSource",destroyMethod = "close",initMethod = "init")
- public DataSource getMasterDs(){
- DruidDataSource druidDataSource = new DruidDataSource();
- druidDataSource.setDriverClassName(driverClassName);
- druidDataSource.setUrl(jdbcUrl);
- druidDataSource.setUsername(username);
- druidDataSource.setPassword(password);
- druidDataSource.setMaxActive(maxActive);
- druidDataSource.setInitialSize(initialSize);
- druidDataSource.setTimeBetweenConnectErrorMillis(timeBetweenEvictionRunsMillis);
- druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
- druidDataSource.setValidationQuery(validationQuery);
- druidDataSource.setTestWhileIdle(testWhileIdle);
- druidDataSource.setTestOnBorrow(testOnBorrow);
- druidDataSource.setTestOnReturn(testOnReturn);
- druidDataSource.setPoolPreparedStatements(poolPreparedStatements);
- druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
- try {
- druidDataSource.setFilters(filters);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return druidDataSource;
- }
-
-
- @Bean
- JdbcTemplate jdbcTemplate(@Qualifier("masterDataSource") DataSource dataSource) {
- //代理数据源配置
- JdbcTemplate jdbcTemplate = new JdbcTemplate(new DataSourceProxy(dataSource));
- return jdbcTemplate;
- }
- }
yml部分配置测试:
- druid-master:
- jdbcUrl: jdbc:mysql://16.2.12.18:3309/paycallback?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
- username: root
- password: 123456
- driver-class-name: com.mysql.jdbc.Driver
- minIdle: 2
- maxActive: 10
- maxWait: 60000
- timeBetweenEvictionRunsMillis: 60000
- minEvictableIdleTimeMillis: 300000
- validationQuery: SELECT 1 FROM DUAL
- testWhileIdle: true
- testOnBorrow: false
- testOnReturn: false
- poolPreparedStatements: true
- maxPoolPreparedStatementPerConnectionSize: 20
- filters: stat,wall
- connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
2、业务代码引用
- @Autowired
- private JdbcTemplate jdbcTemplate;//依赖注入
伪代码段:
- OrderAction orderAction = orderActionMapper.selectByPrimaryKey(Long.parseLong(actionId));
- Order order = orderMapper.selectByPrimaryKey(orderAction.getOrderId());
- String updateOrderSql = "update tp_order_kill set pay_status = ?,pay_time = ? where order_id = ?";
- jdbcTemplate.update(updateOrderSql, new PreparedStatementSetter() {
- @Override
- public void setValues(PreparedStatement ps) throws SQLException {
- ps.setInt(1, PayStatus.PAID.getCode());
- ps.setLong(2, System.currentTimeMillis());
- ps.setLong(3, order.getOrderId());
- }
- });
3、点击 jdbcTemplate.update( 方法:进入jdbcTemplate
- @Override
- public int update(String sql, Object... args) throws DataAccessException {
- return update(sql, newArgPreparedStatementSetter(args));//点击进入
- }
来到:
- @Override
- public int update(String sql, PreparedStatementSetter pss) throws DataAccessException {
- return update(new SimplePreparedStatementCreator(sql), pss);//点击
- }
来到:
- protected int update(final PreparedStatementCreator psc, final PreparedStatementSetter pss)
- throws DataAccessException {
-
- logger.debug("Executing prepared SQL update");
- //点击 进入核心代码
- return execute(psc, new PreparedStatementCallback<Integer>() {
- @Override
- public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
- try {
- if (pss != null) {
- pss.setValues(ps);
- }
- int rows = ps.executeUpdate();//核心代码
- if (logger.isDebugEnabled()) {
- logger.debug("SQL update affected " + rows + " rows");
- }
- return rows;
- }
- finally {
- if (pss instanceof ParameterDisposer) {
- ((ParameterDisposer) pss).cleanupParameters();
- }
- }
- }
- });
- }
4、点击return execute(psc, new PreparedStatementCallback<Integer>() 接口
- @Override
- public <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action)
- throws DataAccessException {
-
- Assert.notNull(psc, "PreparedStatementCreator must not be null");
- Assert.notNull(action, "Callback object must not be null");
- if (logger.isDebugEnabled()) {
- String sql = getSql(psc);
- logger.debug("Executing prepared SQL statement" + (sql != null ? " [" + sql + "]" : ""));
- }
-
- Connection con = DataSourceUtils.getConnection(getDataSource());//核心 getDataSource() 获取的是代理数据源
- PreparedStatement ps = null;
- try {
- Connection conToUse = con;
- if (this.nativeJdbcExtractor != null &&
- this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements()) {
- conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
- }
- ps = psc.createPreparedStatement(conToUse);//重点 获取是代理类
- applyStatementSettings(ps);
- PreparedStatement psToUse = ps;
- if (this.nativeJdbcExtractor != null) {
- psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps);
- }
- T result = action.doInPreparedStatement(psToUse);//执行业务sql
- handleWarnings(ps);
- return result;
- }
- catch (SQLException ex) {
- // Release Connection early, to avoid potential connection pool deadlock
- // in the case when the exception translator hasn't been initialized yet.
- if (psc instanceof ParameterDisposer) {
- ((ParameterDisposer) psc).cleanupParameters();
- }
- String sql = getSql(psc);
- psc = null;
- JdbcUtils.closeStatement(ps);
- ps = null;
- DataSourceUtils.releaseConnection(con, getDataSource());
- con = null;
- throw getExceptionTranslator().translate("PreparedStatementCallback", sql, ex);
- }
- finally {
- if (psc instanceof ParameterDisposer) {
- ((ParameterDisposer) psc).cleanupParameters();
- }
- JdbcUtils.closeStatement(ps);
- DataSourceUtils.releaseConnection(con, getDataSource());
- }
- }
5、点击 getDataSource() 获得代理数据源
- public DataSource getDataSource() {
- return this.dataSource;
- }
点击 psc.createPreparedStatement(conToUse); 进入 PreparedStatementCreatorFactory 工厂
- @Override
- public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
- PreparedStatement ps;
- if (generatedKeysColumnNames != null || returnGeneratedKeys) {
- if (generatedKeysColumnNames != null) {
- ps = con.prepareStatement(this.actualSql, generatedKeysColumnNames);
- }
- else {
- ps = con.prepareStatement(this.actualSql, PreparedStatement.RETURN_GENERATED_KEYS);
- }
- }
- else if (resultSetType == ResultSet.TYPE_FORWARD_ONLY && !updatableResults) {
- ps = con.prepareStatement(this.actualSql);
- }
- else {
- ps = con.prepareStatement(this.actualSql, resultSetType,
- updatableResults ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY);
- }
- setValues(ps);
- return ps;
- }
6、点击 con.prepareStatement 进入 AbstractConnectionProxy 类
7、来到 AbstractConnectionProxy
- @Override
- public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
- PreparedStatement preparedStatement = targetConnection.prepareStatement(sql, autoGeneratedKeys);
- return new PreparedStatementProxy(this, preparedStatement, sql);//点击进入
- }
8、点击 PreparedStatementProxy 进入 代理类:重点
- /**
- * The type Prepared statement proxy.
- *
- * @author sharajava
- *
- * 全局事务流程接着进入到标注有@GlobalTransactional注解的业务方法中,当执行到SQL语句时,由于Seata 对数据源进行了代理,
- * 所以所以的SQL 执行都会进入到其代理方法中。
- * 在JDBC 操作数据库时,执行SQL 语句的是PreparedStatement,在Seata 中其代理类为PreparedStatementProxy,
- * 其execute 方法会调用ExecuteTemplate的execute方法。
- */
- public class PreparedStatementProxy extends AbstractPreparedStatementProxy
- implements PreparedStatement, ParametersHolder {
-
- @Override
- public Map<Integer,ArrayList<Object>> getParameters() {
- return parameters;
- }
-
- /**
- * Instantiates a new Prepared statement proxy.
- *
- * @param connectionProxy the connection proxy
- * @param targetStatement the target statement
- * @param targetSQL the target sql
- * @throws SQLException the sql exception
- */
- public PreparedStatementProxy(AbstractConnectionProxy connectionProxy, PreparedStatement targetStatement,
- String targetSQL) throws SQLException {
- super(connectionProxy, targetStatement, targetSQL);
- }
-
- @Override
- public boolean execute() throws SQLException {//重点接口
- return ExecuteTemplate.execute(this, (statement, args) -> statement.execute());
- }
-
- @Override
- public ResultSet executeQuery() throws SQLException {
- return ExecuteTemplate.execute(this, (statement, args) -> statement.executeQuery());
- }
-
- @Override
- public int executeUpdate() throws SQLException {
- return ExecuteTemplate.execute(this, (statement, args) -> statement.executeUpdate());
- }
- }
9、此类里面有很多业务接口,比如:
- @Override
- public boolean execute() throws SQLException {//重点接口
- return ExecuteTemplate.execute(this, (statement, args) -> statement.execute());
- }
何时调用到此类接口呢?
10、返回上游看看 action.doInPreparedStatement(psToUse);进入 AbstractLobCreatingPreparedStatementCallback
- @Override
- public final Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
- LobCreator lobCreator = this.lobHandler.getLobCreator();
- try {
- setValues(ps, lobCreator);
- return ps.executeUpdate();//点击进入
- }
- finally {
- lobCreator.close();
- }
- }
11、点击 ps.executeUpdate() 进入
肯定是进入这里,因为上游已经生成了这个对象 PreparedStatementProxy
- @Override
- public int executeUpdate() throws SQLException {
- return ExecuteTemplate.execute(this, (statement, args) -> statement.executeUpdate());//点击进入
- }
12、点击 ExecuteTemplate.execute接口
- public static <T, S extends Statement> T execute(StatementProxy<S> statementProxy,
- StatementCallback<T, S> statementCallback,
- Object... args) throws SQLException {
- return execute(null, statementProxy, statementCallback, args);//进入核心方法
- }
继续进入
- /**
- * Execute t.
- *
- * @param <T> the type parameter
- * @param <S> the type parameter
- * @param sqlRecognizers the sql recognizer list
- * @param statementProxy the statement proxy
- * @param statementCallback the statement callback
- * @param args the args
- * @return the t
- * @throws SQLException the sql exception
- * ExecuteTemplate中,会根据不同的SQL 操作类型创建不同的执行器:
- */
- public static <T, S extends Statement> T execute(List<SQLRecognizer> sqlRecognizers,
- StatementProxy<S> statementProxy,
- StatementCallback<T, S> statementCallback,
- Object... args) throws SQLException {
- // 如果没有全局锁,并且不是AT模式,直接执行SQL
- if (!RootContext.requireGlobalLock() && BranchType.AT != RootContext.getBranchType()) {
- // Just work as original statement
- return statementCallback.execute(statementProxy.getTargetStatement(), args);
- }
- // 得到数据库类型 ->MySQL
- String dbType = statementProxy.getConnectionProxy().getDbType();
- // 3. 获取执行的SQL ,将SQL 解析为表达式(SQL 解析器) ,sqlRecognizers参数初始为NULL,所以这里都需要获取,
- // 普通SELECT 查询这里为null, 增删改都会解析出对应的SQL表达式
- if (CollectionUtils.isEmpty(sqlRecognizers)) {
- //sqlRecognizers为SQL语句的解析器,获取执行的SQL,通过它可以获得SQL语句表名、相关的列名、类型的等信息,最后解析出对应的SQL表达式
- sqlRecognizers = SQLVisitorFactory.get(
- statementProxy.getTargetSQL(),
- dbType);
- }
- Executor<T> executor;
- if (CollectionUtils.isEmpty(sqlRecognizers)) {
- //如果seata没有找到合适的SQL语句解析器,那么便创建简单执行器PlainExecutor,
- //PlainExecutor直接使用原生的Statement对象执行SQL
- executor = new PlainExecutor<>(statementProxy, statementCallback);
- } else {
- if (sqlRecognizers.size() == 1) {
- SQLRecognizer sqlRecognizer = sqlRecognizers.get(0);
- switch (sqlRecognizer.getSQLType()) {
- //下面根据是增、删、改、加锁查询、普通查询分别创建对应的处理器
- case INSERT:
- executor = EnhancedServiceLoader.load(InsertExecutor.class, dbType,
- new Class[]{StatementProxy.class, StatementCallback.class, SQLRecognizer.class},
- new Object[]{statementProxy, statementCallback, sqlRecognizer});
- break;
- case UPDATE:
- executor = new UpdateExecutor<>(statementProxy, statementCallback, sqlRecognizer);
- break;
- case DELETE:
- executor = new DeleteExecutor<>(statementProxy, statementCallback, sqlRecognizer);
- break;
- case SELECT_FOR_UPDATE:// 排它锁语句
- executor = new SelectForUpdateExecutor<>(statementProxy, statementCallback, sqlRecognizer);
- break;
- default:
- executor = new PlainExecutor<>(statementProxy, statementCallback);
- break;
- }
- } else {
- // 此执行器可以处理一条SQL语句包含多个Delete、Update语句
- executor = new MultiExecutor<>(statementProxy, statementCallback, sqlRecognizers);
- }
- }
- T rs;
- try {// 执行器执行,钩子方法,这里调用的子类BaseTransactionalExecutor的方法, 更新时使用的是UpdateExecutor
- rs = executor.execute(args);//点击进入
- } catch (Throwable ex) {
- if (!(ex instanceof SQLException)) {
- // Turn other exception into SQLException
- ex = new SQLException(ex);
- }
- throw (SQLException) ex;
- }
- return rs;
- }
13、点击 executor.execute(args) 进入 BaseTransactionalExecutor 类
- @Override
- public T execute(Object... args) throws Throwable {
- String xid = RootContext.getXID();// 获取xid
- if (xid != null) {
- statementProxy.getConnectionProxy().bind(xid);
- }
- // 设置全局锁
- statementProxy.getConnectionProxy().setGlobalLockRequire(RootContext.requireGlobalLock());
- return doExecute(args);//进入子类 AbstractDMLBaseExecutor 重写的方法
- }
14、点击 doExecute(args) 进入 AbstractDMLBaseExecutor
来到
- @Override
- public T doExecute(Object... args) throws Throwable {
- AbstractConnectionProxy connectionProxy = statementProxy.getConnectionProxy();//取出代理数据源
- //数据库本身是自动提交,取出代理数据源后,如果拿到执行操作数据库的指令,则进行数据库的操作,进入
- if (connectionProxy.getAutoCommit()) {
- return executeAutoCommitTrue(args);
- } else {//如果没有拿到,先不提交,进入
- return executeAutoCommitFalse(args);
- }
- }
15、点击 executeAutoCommitTrue(args)
- protected T executeAutoCommitTrue(Object[] args) throws Throwable {
- ConnectionProxy connectionProxy = statementProxy.getConnectionProxy();
- try {// 更改为手动提交,关闭自动提交,保证业务sql和undo_log里的sql执行在同一个事务里面
- connectionProxy.changeAutoCommit();
- //重试策略提交本地事务,cas思想
- // 3. 使用LockRetryPolicy.execute 开启一条线程去执行,LockRetryPolicy 是一个策略,
- // 策略对应配置retry-policy-branch-rollback-on-conflict
- // 分支事务与其它全局回滚事务冲突时锁策略,默认true,优先释放本地锁让回滚成功
- return new LockRetryPolicy(connectionProxy).execute(() -> {
- // 调用手动提交方法 得到分支业务最终结果
- //解析 sql,查询 beforeImage 执行前的结果集(这里有一个 for update 加一个本地锁),执行业务 sql,查询 afterImage 执行后的结果集
- T result = executeAutoCommitFalse(args);
- //获取全局锁、插入 undo_log 日志、业务 sql 和 undo_log 的事务提交,核心代码,进入
- connectionProxy.commit(); // 执行提交
- return result;
- });
- } catch (Exception e) {
- // when exception occur in finally,this exception will lost, so just print it here
- LOGGER.error("execute executeAutoCommitTrue error:{}", e.getMessage(), e);
- if (!LockRetryPolicy.isLockRetryPolicyBranchRollbackOnConflict()) {
- connectionProxy.getTargetConnection().rollback();
- }
- throw e;
- } finally {
- // 清理资源,设置提供提交为true
- connectionProxy.getContext().reset();
- connectionProxy.setAutoCommit(true);
- }
- }
16、点击 connectionProxy.commit();进入 ConnectionProxy
- @Override
- public void commit() throws SQLException {
- try {
- LOCK_RETRY_POLICY.execute(() -> {
- doCommit();//核心代码
- return null;
- });
- } catch (SQLException e) {
- if (targetConnection != null && !getAutoCommit() && !getContext().isAutoCommitChanged()) {
- rollback();
- }
- throw e;
- } catch (Exception e) {
- throw new SQLException(e);
- }
- }
点击 doCommit()
- private void doCommit() throws SQLException {
- if (context.inGlobalTransaction()) {//判断是否存在全局事务
- processGlobalTransactionCommit();//全局事务业务提交,进入
- } else if (context.isGlobalLockRequire()) { // 如果是GlobalLock
- processLocalCommitWithGlobalLocks();
- } else {
- targetConnection.commit();//原数据源直接提交
- }
- }
17、点击 processGlobalTransactionCommit()方法
- private void processGlobalTransactionCommit() throws SQLException {
- try {
- /**
- * 跟 TC 通讯,申请一把全局锁,算是分布式锁(只不过是用关系型数据库做的而已),其实就是往 lock_table 中插入一条记录,插入成功则加锁成功
- * TC端(server端) 核心代码在这server包里 public class LockStoreDataBaseDAO implements LockStore,
- * 有兴趣可以往下找,均是公用的远程调用接口,后续会深入分析
- */
- register(); // 和TC端通信 注册分支,重点
- } catch (TransactionException e) {
- recognizeLockKeyConflictException(e, context.buildLockKeys());
- }
- try {//写入数据库undolog
- //如果有 undo_log 记录则插入 undo_log 表,会根据 undo_log 来做二阶段回滚,进入
- UndoLogManagerFactory.getUndoLogManager(this.getDbType()).flushUndoLogs(this);
- //本地事务彻底提交,注意这里 undo_log 和业务 sql 是同一个事务的。此处成功代表此RM执行成功,并释放本地锁。
- targetConnection.commit();//执行最原生业务sql提交
- } catch (Throwable ex) {
- LOGGER.error("process connectionProxy commit error: {}", ex.getMessage(), ex);
- report(false);//此处成功后和TC 通讯,报告分支事务的执行失败的结果
- throw new SQLException(ex);
- }
- if (IS_REPORT_SUCCESS_ENABLE) {
- report(true);//此处成功后和TC 通讯,报告分支事务的执行成功的结果
- }
- context.reset();
- }
点击 register()
- // 注册分支事务,生成分支事务id
- private void register() throws TransactionException {
- if (!context.hasUndoLog() || !context.hasLockKey()) {
- return;
- }// 注册分支事务
- //在事务提交以前,会注册本地事务,最后调用的是 AbstractResourceManager的branchRegister 方法,向TC 发送请求
- Long branchId = DefaultResourceManager.get().branchRegister(BranchType.AT, getDataSourceProxy().getResourceId(),
- null, context.getXid(), null, context.buildLockKeys());
- context.setBranchId(branchId);//分支事务id添加到上下文中
- }
18、点击 branchRegister 方法进入 DefaultResourceManager
- @Override
- public Long branchRegister(BranchType branchType, String resourceId,
- String clientId, String xid, String applicationData, String lockKeys)
- throws TransactionException {
- //AbstractResourceManager 进入
- return getResourceManager(branchType).branchRegister(branchType, resourceId, clientId, xid, applicationData,
- lockKeys);
- }
19、点击 branchRegister 方法 进入 AbstractResourceManager
- @Override
- public Long branchRegister(BranchType branchType, String resourceId, String clientId, String xid, String applicationData, String lockKeys) throws TransactionException {
- try {
- BranchRegisterRequest request = new BranchRegisterRequest();
- request.setXid(xid);
- request.setLockKey(lockKeys);
- request.setResourceId(resourceId);
- request.setBranchType(branchType);
- request.setApplicationData(applicationData);
-
- /**
- * TC 中,负责注册分支的是 AbstractCore 的 branchRegister 方法,其中最重要的一步就是获取该分支事务的全局锁。
- */
- BranchRegisterResponse response = (BranchRegisterResponse) RmNettyRemotingClient.getInstance().sendSyncRequest(request);
- if (response.getResultCode() == ResultCode.Failed) {
- throw new RmTransactionException(response.getTransactionExceptionCode(), String.format("Response[ %s ]", response.getMsg()));
- }
- return response.getBranchId();
- } catch (TimeoutException toe) {
- throw new RmTransactionException(TransactionExceptionCode.IO, "RPC Timeout", toe);
- } catch (RuntimeException rex) {
- throw new RmTransactionException(TransactionExceptionCode.BranchRegisterFailed, "Runtime", rex);
- }
- }
20、点击 sendSyncRequest 方法 进入 AbstractNettyRemotingClient
- @Override
- public Object sendSyncRequest(Object msg) throws TimeoutException {
- //通过事务组,负载选择一个服务端实例
- String serverAddress = loadBalance(getTransactionServiceGroup(), msg);
- int timeoutMillis = NettyClientConfig.getRpcRequestTimeout();//超时时间设置
- RpcMessage rpcMessage = buildRequestMessage(msg, ProtocolConstants.MSGTYPE_RESQUEST_SYNC);
-
- // send batch message
- // put message into basketMap, @see MergedSendRunnable
- if (NettyClientConfig.isEnableClientBatchSendRequest()) {
-
- // send batch message is sync request, needs to create messageFuture and put it in futures.
- MessageFuture messageFuture = new MessageFuture();
- messageFuture.setRequestMessage(rpcMessage);
- messageFuture.setTimeout(timeoutMillis);
- futures.put(rpcMessage.getId(), messageFuture);
-
- // put message into basketMap
- BlockingQueue<RpcMessage> basket = CollectionUtils.computeIfAbsent(basketMap, serverAddress,
- key -> new LinkedBlockingQueue<>());
- if (!basket.offer(rpcMessage)) {
- LOGGER.error("put message into basketMap offer failed, serverAddress:{},rpcMessage:{}",
- serverAddress, rpcMessage);
- return null;
- }
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("offer message: {}", rpcMessage.getBody());
- }
- if (!isSending) {
- synchronized (mergeLock) {
- mergeLock.notifyAll();
- }
- }
-
- try {
- return messageFuture.get(timeoutMillis, TimeUnit.MILLISECONDS);
- } catch (Exception exx) {
- LOGGER.error("wait response error:{},ip:{},request:{}",
- exx.getMessage(), serverAddress, rpcMessage.getBody());
- if (exx instanceof TimeoutException) {
- throw (TimeoutException) exx;
- } else {
- throw new RuntimeException(exx);
- }
- }
-
- } else {
- Channel channel = clientChannelManager.acquireChannel(serverAddress);
- //正式继续调用
- return super.sendSync(channel, rpcMessage, timeoutMillis);
- }
-
- }
21、点击 super.sendSync(channel, rpcMessage, timeoutMillis)进入 AbstractNettyRemoting
- protected Object sendSync(Channel channel, RpcMessage rpcMessage, long timeoutMillis) throws TimeoutException {
- if (timeoutMillis <= 0) {
- throw new FrameworkException("timeout should more than 0ms");
- }
- if (channel == null) {
- LOGGER.warn("sendSync nothing, caused by null channel.");
- return null;
- }
-
- MessageFuture messageFuture = new MessageFuture();
- messageFuture.setRequestMessage(rpcMessage);
- messageFuture.setTimeout(timeoutMillis);
- futures.put(rpcMessage.getId(), messageFuture);
-
- channelWritableCheck(channel, rpcMessage.getBody());
-
- String remoteAddr = ChannelUtil.getAddressFromChannel(channel);
- doBeforeRpcHooks(remoteAddr, rpcMessage);
- //正式通过netty的writeAndFlush 标准接口调用,并监听
- channel.writeAndFlush(rpcMessage).addListener((ChannelFutureListener) future -> {
- if (!future.isSuccess()) {
- MessageFuture messageFuture1 = futures.remove(rpcMessage.getId());
- if (messageFuture1 != null) {
- messageFuture1.setResultMessage(future.cause());
- }
- destroyChannel(future.channel());
- }
- });
-
- try {//异步获取调用结果
- Object result = messageFuture.get(timeoutMillis, TimeUnit.MILLISECONDS);
- doAfterRpcHooks(remoteAddr, rpcMessage, result);
- return result;
- } catch (Exception exx) {
- LOGGER.error("wait response error:{},ip:{},request:{}", exx.getMessage(), channel.remoteAddress(),
- rpcMessage.getBody());
- if (exx instanceof TimeoutException) {
- throw (TimeoutException) exx;
- } else {
- throw new RuntimeException(exx);
- }
- }
- }
到这里客户端流程结束,下游就是TC端接受信息了,下篇我们会详细分享。
22、上游 存日志操作 UndoLogManagerFactory.getUndoLogManager(this.getDbType()).flushUndoLogs(this);
进入 AbstractUndoLogManager implements UndoLogManager 类
- @Override
- public void flushUndoLogs(ConnectionProxy cp) throws SQLException {
- ConnectionContext connectionContext = cp.getContext();
- if (!connectionContext.hasUndoLog()) {
- return;
- }
-
- String xid = connectionContext.getXid();
- long branchId = connectionContext.getBranchId();
-
- BranchUndoLog branchUndoLog = new BranchUndoLog();
- branchUndoLog.setXid(xid);
- branchUndoLog.setBranchId(branchId);
- branchUndoLog.setSqlUndoLogs(connectionContext.getUndoItems());
-
- UndoLogParser parser = UndoLogParserFactory.getInstance();
- byte[] undoLogContent = parser.encode(branchUndoLog);
-
- CompressorType compressorType = CompressorType.NONE;
- if (needCompress(undoLogContent)) {
- compressorType = ROLLBACK_INFO_COMPRESS_TYPE;
- undoLogContent = CompressorFactory.getCompressor(compressorType.getCode()).compress(undoLogContent);
- }
-
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Flushing UNDO LOG: {}", new String(undoLogContent, Constants.DEFAULT_CHARSET));
- }
- // 写入数据库具体位置,点击进入
-
- insertUndoLogWithNormal(xid, branchId, buildContext(parser.getName(), compressorType), undoLogContent, cp.getTargetConnection());
- }
23、点击 insertUndoLogWithNormal 进入
我们用的mysql数据库,因此进入这里 MySQLUndoLogManager extends AbstractUndoLogManager
- @Override
- protected void insertUndoLogWithNormal(String xid, long branchId, String rollbackCtx, byte[] undoLogContent,
- Connection conn) throws SQLException {
- insertUndoLog(xid, branchId, rollbackCtx, undoLogContent, State.Normal, conn);//进入
- }
到了原始数据执行
- private void insertUndoLog(String xid, long branchId, String rollbackCtx, byte[] undoLogContent,
- State state, Connection conn) throws SQLException {
- try (PreparedStatement pst = conn.prepareStatement(INSERT_UNDO_LOG_SQL)) {
- pst.setLong(1, branchId);
- pst.setString(2, xid);
- pst.setString(3, rollbackCtx);
- pst.setBytes(4, undoLogContent);
- pst.setInt(5, state.getValue());
- pst.executeUpdate();//反sql添加,
- } catch (Exception e) {
- if (!(e instanceof SQLException)) {
- e = new SQLException(e);
- }
- throw (SQLException) e;
- }
- }
24、上游 report(true);//此处成功后和TC 通讯,报告分支事务的执行成功的结果,和其他的TC通信类似
- private void report(boolean commitDone) throws SQLException {
- if (context.getBranchId() == null) {
- return;
- }
- int retry = REPORT_RETRY_COUNT;
- while (retry > 0) {
- try {
- //开始调用,到此,流程类似
- DefaultResourceManager.get().branchReport(BranchType.AT, context.getXid(), context.getBranchId(),
- commitDone ? BranchStatus.PhaseOne_Done : BranchStatus.PhaseOne_Failed, null);
- return;
- } catch (Throwable ex) {
- LOGGER.error("Failed to report [" + context.getBranchId() + "/" + context.getXid() + "] commit done ["
- + commitDone + "] Retry Countdown: " + retry);
- retry--;
-
- if (retry == 0) {
- throw new SQLException("Failed to report branch status " + commitDone, ex);
- }
- }
- }
- }
25、返回上游 return executeAutoCommitFalse(args); 如果没有拿到操作数据库的指令或者拿到操作指令时也有这一步操作:
- /**
- * Execute auto commit false t.
- *
- * @param args the args
- * @return the t
- * @throws Exception the exception
- * 不自动提交执行,会在SQL 实际执行前后,构建镜像,记录数据状态,比如更新语句,会记录该条数据修改前和修改后的数据状态,并添加排他锁
- */
- protected T executeAutoCommitFalse(Object[] args) throws Exception {
- if (!JdbcConstants.MYSQL.equalsIgnoreCase(getDbType()) && isMultiPk()) {
- throw new NotSupportYetException("multi pk only support mysql!");
- }
- //解析业务 sql,根据业务 sql 的条件拼凑 select 语句,查询执行业务 sql 之前的结果,会根据这个结果来做二阶段回滚,即此处加行锁,本地锁
- //可以进入 UpdateExecutor
- TableRecords beforeImage = beforeImage();//前置镜像数据,进入 UpdateExecutor 子类
- //执行业务sql
- T result = statementCallback.execute(statementProxy.getTargetStatement(), args);
- //根据 beforeImage 的结果集的注解 ID 拼凑 select 语句,以这个主键 id 作为条件查询
- TableRecords afterImage = afterImage(beforeImage);//后置镜像数据,可以进入更新 MultiUpdateExecutor
- //把 beforeImage 和 afterImage 包装到一个对象中,并装入 list 中,后续插入undo_log 表
- prepareUndoLog(beforeImage, afterImage);
- return result;
- }
点击 beforeImage() 进入 UpdateExecutor 类
- @Override
- protected TableRecords beforeImage() throws SQLException {
- ArrayList<List<Object>> paramAppenderList = new ArrayList<>();
- TableMeta tmeta = getTableMeta();//拿到一些表的信息
- String selectSQL = buildBeforeImageSQL(tmeta, paramAppenderList);//拼凑sql,同时加行锁,进入
- return buildTableRecords(tmeta, selectSQL, paramAppenderList);//操作数据库的核心代码
- }
点击 getTableMeta();//拿到一些表的信息,
BaseTransactionalExecutor<T, S extends Statement> implements Executor<T>
- protected TableMeta getTableMeta() {
- return getTableMeta(sqlRecognizer.getTableName());//继续进入
- }
进入
- protected TableMeta getTableMeta(String tableName) {
- if (tableMeta != null) {
- return tableMeta;
- }
- ConnectionProxy connectionProxy = statementProxy.getConnectionProxy();
- //通过数据源代理,获取表的数据.....
- tableMeta = TableMetaCacheFactory.getTableMetaCache(connectionProxy.getDbType())
- .getTableMeta(connectionProxy.getTargetConnection(), tableName, connectionProxy.getDataSourceProxy().getResourceId());
- return tableMeta;
- }
点击 getTableMeta( 进入
- @Override
- public TableMeta getTableMeta(final Connection connection, final String tableName, String resourceId) {
- if (StringUtils.isNullOrEmpty(tableName)) {
- throw new IllegalArgumentException("TableMeta cannot be fetched without tableName");
- }
-
- TableMeta tmeta;
- final String key = getCacheKey(connection, tableName, resourceId);
- tmeta = TABLE_META_CACHE.get(key, mappingFunction -> {
- try {
- return fetchSchema(connection, tableName);//获取数据库资源
- } catch (SQLException e) {
- LOGGER.error("get table meta of the table `{}` error: {}", tableName, e.getMessage(), e);
- return null;
- }
- });
-
- if (tmeta == null) {
- throw new ShouldNeverHappenException(String.format("[xid:%s]get table meta failed," +
- " please check whether the table `%s` exists.", RootContext.getXID(), tableName));
- }
- return tmeta;
- }
点击 fetchSchema(connection, tableName);//获取数据库资源 ,进入MysqlTableMetaCache
- @Override
- protected TableMeta fetchSchema(Connection connection, String tableName) throws SQLException {
- String sql = "SELECT * FROM " + ColumnUtils.addEscape(tableName, JdbcConstants.MYSQL) + " LIMIT 1";
- try (Statement stmt = connection.createStatement();//创建获取声明的代理
- ResultSet rs = stmt.executeQuery(sql)) {
- return resultSetMetaToSchema(rs.getMetaData(), connection.getMetaData());
- } catch (SQLException sqlEx) {
- throw sqlEx;
- } catch (Exception e) {
- throw new SQLException(String.format("Failed to fetch schema of %s", tableName), e);
- }
- }
点击buildBeforeImageSQL(tmeta, paramAppenderList);悲观锁在这里添加
- private String buildBeforeImageSQL(TableMeta tableMeta, ArrayList<List<Object>> paramAppenderList) {
- SQLUpdateRecognizer recognizer = (SQLUpdateRecognizer) sqlRecognizer;
- List<String> updateColumns = recognizer.getUpdateColumns();
- StringBuilder prefix = new StringBuilder("SELECT ");
- StringBuilder suffix = new StringBuilder(" FROM ").append(getFromTableInSQL());
- String whereCondition = buildWhereCondition(recognizer, paramAppenderList);
- if (StringUtils.isNotBlank(whereCondition)) {
- suffix.append(WHERE).append(whereCondition);
- }
- String orderBy = recognizer.getOrderBy();
- if (StringUtils.isNotBlank(orderBy)) {
- suffix.append(orderBy);
- }
- ParametersHolder parametersHolder = statementProxy instanceof ParametersHolder ? (ParametersHolder)statementProxy : null;
- String limit = recognizer.getLimit(parametersHolder, paramAppenderList);
- if (StringUtils.isNotBlank(limit)) {
- suffix.append(limit);
- }
- suffix.append(" FOR UPDATE");//添加悲观锁
- StringJoiner selectSQLJoin = new StringJoiner(", ", prefix.toString(), suffix.toString());
- if (ONLY_CARE_UPDATE_COLUMNS) {
- if (!containsPK(updateColumns)) {
- selectSQLJoin.add(getColumnNamesInSQL(tableMeta.getEscapePkNameList(getDbType())));
- }
- for (String columnName : updateColumns) {
- selectSQLJoin.add(columnName);
- }
- } else {
- for (String columnName : tableMeta.getAllColumns().keySet()) {
- selectSQLJoin.add(ColumnUtils.addEscape(columnName, getDbType()));
- }
- }
- return selectSQLJoin.toString();
- }
点击 buildTableRecords(
- protected TableRecords buildTableRecords(TableMeta tableMeta, String selectSQL, ArrayList<List<Object>> paramAppenderList) throws SQLException {
- ResultSet rs = null;
- try (PreparedStatement ps = statementProxy.getConnection().prepareStatement(selectSQL)) {//点击进入
- if (CollectionUtils.isNotEmpty(paramAppenderList)) {
- for (int i = 0, ts = paramAppenderList.size(); i < ts; i++) {
- List<Object> paramAppender = paramAppenderList.get(i);
- for (int j = 0, ds = paramAppender.size(); j < ds; j++) {
- ps.setObject(i * ds + j + 1, paramAppender.get(j));
- }
- }
- }
- rs = ps.executeQuery();
- return TableRecords.buildRecords(tableMeta, rs);
- } finally {
- IOUtil.close(rs);
- }
- }
26、点击 getConnection().prepareStatement(selectSQL)) {//点击进入
AbstractConnectionProxy implements Connection
- @Override
- public PreparedStatement prepareStatement(String sql) throws SQLException {
- String dbType = getDbType();//数据库类型,比如mysql、oracle等
- // support oracle 10.2+
- PreparedStatement targetPreparedStatement = null;
- if (BranchType.AT == RootContext.getBranchType()) { //如果是AT模式且开启全局事务,那么就会进入if分支
- List<SQLRecognizer> sqlRecognizers = SQLVisitorFactory.get(sql, dbType);
- if (sqlRecognizers != null && sqlRecognizers.size() == 1) {
- SQLRecognizer sqlRecognizer = sqlRecognizers.get(0);
- if (sqlRecognizer != null && sqlRecognizer.getSQLType() == SQLType.INSERT) {
- //得到表的元数据
- TableMeta tableMeta = TableMetaCacheFactory.getTableMetaCache(dbType).getTableMeta(getTargetConnection(),
- sqlRecognizer.getTableName(), getDataSourceProxy().getResourceId());
- //得到表的主键列名
- String[] pkNameArray = new String[tableMeta.getPrimaryKeyOnlyName().size()];
- tableMeta.getPrimaryKeyOnlyName().toArray(pkNameArray);
- targetPreparedStatement = getTargetConnection().prepareStatement(sql,pkNameArray);
- }
- }
- }
- if (targetPreparedStatement == null) {
- targetPreparedStatement = getTargetConnection().prepareStatement(sql);
- }// 创建PreparedStatementProxy代理
- return new PreparedStatementProxy(this, targetPreparedStatement, sql);
- }
27、afterImage(beforeImage);流程同上;点击 prepareUndoLog(beforeImage, afterImage);
- protected void prepareUndoLog(TableRecords beforeImage, TableRecords afterImage) throws SQLException {
- // 前后镜像都为空,执行返回
- if (beforeImage.getRows().isEmpty() && afterImage.getRows().isEmpty()) {
- return;
- }
- // UPDATE 时,没有前后镜像,抛出异常
- if (SQLType.UPDATE == sqlRecognizer.getSQLType()) {
- if (beforeImage.getRows().size() != afterImage.getRows().size()) {
- throw new ShouldNeverHappenException("Before image size is not equaled to after image size, probably because you updated the primary keys.");
- }
- }
- ConnectionProxy connectionProxy = statementProxy.getConnectionProxy();
- // 如果是删除,则只记录删除前的数据
- TableRecords lockKeyRecords = sqlRecognizer.getSQLType() == SQLType.DELETE ? beforeImage : afterImage;
- // 构建全局锁的key =>account_tbl:11111111(表名+主键 )
- String lockKeys = buildLockKey(lockKeyRecords);
- if (null != lockKeys) {
- // 添加全局锁的KEY 和滚回日志到 SQL 连接中
- connectionProxy.appendLockKey(lockKeys);
-
- SQLUndoLog sqlUndoLog = buildUndoItem(beforeImage, afterImage);
- connectionProxy.appendUndoLog(sqlUndoLog);
- }
- }
28、TC端介绍开始:
TC的业务内部类channelHandler为类 io.seata.core.rpc.netty.AbstractNettyRemotingServer.ServerHandler
到此、客户端数据源初始化和执行的源码流程分析完成,下篇我们分析服务端接收的源码,敬请期待!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。