分布式事务实战(三) -Spring事务及代码案例实现

2021-02-23 14:57:12 浏览数 (1)

1 事务管理

  • 提供的统一的API接口支持不同的资源
  • 提供声明式事务管理
  • 方便的与Spring框架集成
  • 多个资源的事务管理、同步

2 事务抽象

2.1 事务管理器 - PlatformTransactionManager

代码语言:javascript复制
public interface PlatformTransactionManager {
	TransactionStatus getTransaction(TransactionDefinition definition)
throws TransactionException;
	void commit(TransactionStatus status) throws TransactionException;
	void rollback(TransactionStatus status) throws TransactionException;
}	

2.2 事务定义 - TransactionDefinition

代码语言:javascript复制
public interface TransactionDefinition {
	int getPropagationBehavior();
	int getlsolationLevel();
	String getName();
	int getTimeout();
	boolean isReadOnly();
}

2.3 事务隔离机制

代码语言:javascript复制
TransactionDefinition.ISOlATION_DEFAULT
TransactionDefinition.ISOLATION_ READ_ COMMITTED
TransactionDefinition.ISOLATION READ_ UNCOMMITTED
TransactionDefinition.ISOLATION_REPEATABLE_ READ
TransactionDefinition.ISOLATION SERIALIZABLE

2.4 事务传播机制

代码语言:javascript复制
TransactionDefinition.PROPAGATION_ REQUIRED (Default)
TransactionDefinition.PROPAGATION SUPPORTS
TransactionDefinition.PROPAGATION MANDATORY
TransactionDefinition.PROPAGATION REQUIRES NEW
TransactionDefinition.PROPAGATION NOT _SUPPORTED
TransactionDefinition.PROPAGATION NEVER
TransactionDefinition.PROPAGATION NESTEDED
  • REQUIRED 适用于增删改
  • SUPPORTS 适用于查询。

2.5 TransactionStatus

代码语言:javascript复制
public interface TransactionStatus extends SavepointManager {
	boolean isNewTransaction();
	boolean hasSavepoint();
	void setRollbackOnly();
	boolean isRollbackOnly();
	boolean isCompleted();
}

3 代码实战

代码语言:javascript复制
public OrderService {
	@Autowire PlatformTransactionManager txManager
	void buyTicket(BuyTicketDTO dto) {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);
		try {
			//执行业务代码
			txManager.commit(status);
		} catch (Exception e) {
			txManager.rollback(status);
		}
	}	
}	

Transactional标签方式实现1

代码语言:javascript复制
public OrderService {
	@Transactonal
	void buyTicket(BuyTicketDTO dto) {
	/ save order
	// finish customer pay
	// transfer tickets
	}
}	

Transactional标签方式实现2

代码语言:javascript复制
public OrderServiceProxy {
	void buyTicket(BuyTicketDTO dto) {
		// get and begin transaction manager from context
		try{
			orderServicelmpl.buyTicket(dto);
			// commit transaction
		} catch (Exceptione) {
			// roolbback transaction
	}
}	
  • 执行原理流程图

PlatformTransactionManager的常见实现

  • DataSourceTransactionManager
  • JpaTransactionManager
  • JmsTransactionManager、
  • JtaTransactionManager

4 工程实战

0 人点赞