001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.support.seata.tcc; 017 018import com.jfinal.aop.Interceptor; 019import com.jfinal.aop.Invocation; 020import io.jboot.support.seata.JbootSeataManager; 021import io.seata.common.util.StringUtils; 022import io.seata.core.context.RootContext; 023import io.seata.core.model.BranchType; 024import io.seata.rm.tcc.api.TwoPhaseBusinessAction; 025 026import java.lang.reflect.Method; 027 028 029/** 030 * TCC Interceptor 031 * <p> 032 * 参考: https://github.com/seata/seata/blob/develop/spring/src/main/java/io/seata/spring/tcc/TccActionInterceptor.java 033 * 034 * @author zhangsen 035 */ 036public class TccActionInterceptor implements Interceptor { 037 038 039 private ActionInterceptorHandler actionInterceptorHandler = new ActionInterceptorHandler(); 040 041 042 @Override 043 public void intercept(Invocation inv) { 044 045 if (!JbootSeataManager.me().isEnable()) { 046 inv.invoke(); 047 return; 048 } 049 050 if (!RootContext.inGlobalTransaction()) { 051 // not in transaction 052 inv.invoke(); 053 return; 054 } 055 056 Method method = inv.getMethod(); 057 TwoPhaseBusinessAction businessAction = method.getAnnotation(TwoPhaseBusinessAction.class); 058 //try method 059 if (businessAction != null) { 060 //save the xid 061 String xid = RootContext.getXID(); 062 //clear the context 063 BranchType previousBranchType = RootContext.getBranchType(); 064 if (BranchType.TCC != previousBranchType) { 065 RootContext.bindBranchType(BranchType.TCC); 066 } 067 try { 068 Object[] methodArgs = inv.getArgs(); 069 //Handler the TCC Aspect 070 actionInterceptorHandler.proceed(method, methodArgs, xid, businessAction, inv); 071 } finally { 072 //if not TCC, unbind branchType 073 if (BranchType.TCC != previousBranchType) { 074 RootContext.unbindBranchType(); 075 } 076 } 077 } else { 078 inv.invoke(); 079 } 080 } 081 082}