開發中,我們一般會利用AOP配置全局性的事務,對指定包下指定的方法(如add,update等)進行事務控制,在springboot中如何實現呢?
@EnableTransactionManagement
@Aspect
@Configuration
public class GlobalTransactionConfig {
//寫事務的超時時間為10秒
private static final int TX_METHOD_TIMEOUT = 10;
//restful包下所有service包或者service的子包的任意類的任意方法
private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.jun.cloud.restful..*.service..*.*(..))";
@Autowired
private PlatformTransactionManager transactionManager;
@Bean
public TransactionInterceptor txAdvice() {
/** * 這里配置只讀事務 */
RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
readOnlyTx.setReadOnly(true);
readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
/** * 必須帶事務 * 當前存在事務就使用當前事務,當前不存在事務,就開啟一個新的事務 */
RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
//檢查型異常也回滾
requiredTx.setRollbackRules(
Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
requiredTx.setTimeout(TX_METHOD_TIMEOUT);
/*** * 無事務地執行,掛起任何存在的事務 */
RuleBasedTransactionAttribute noTx = new RuleBasedTransactionAttribute();
noTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
Map<String, TransactionAttribute> txMap = new HashMap<>();
//只讀事務
txMap.put("get*", readOnlyTx);
txMap.put("query*", readOnlyTx);
txMap.put("find*", readOnlyTx);
txMap.put("list*", readOnlyTx);
txMap.put("count*", readOnlyTx);
txMap.put("exist*", readOnlyTx);
txMap.put("search*", readOnlyTx);
txMap.put("fetch*", readOnlyTx);
//無事務
txMap.put("noTx*", noTx);
//寫事務
txMap.put("add*", requiredTx);
txMap.put("save*", requiredTx);
txMap.put("insert*", requiredTx);
txMap.put("update*", requiredTx);
txMap.put("modify*", requiredTx);
txMap.put("delete*", requiredTx);
NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
source.setNameMap(txMap);
return new TransactionInterceptor(transactionManager, source);
}
@Bean
public Advisor txAdviceAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut, txAdvice());
}
}
如果配置了多個事務管理器,參看https://blog.csdn.net/catoop/article/details/50595702