声明式事务实现示例

考虑以下接口及其伴随实现。本示例使用 FooBar 类作为占位符,以便您可以专注于事务的使用而无需关注特定的领域模型。对于本示例,DefaultFooService 类在每个已实现方法的主体中抛出 UnsupportedOperationException 实例这一事实是好的。这种行为让您可以看到事务的创建,然后响应 UnsupportedOperationException 实例而回滚。以下列表显示了 FooService 接口

  • Java

  • Kotlin

// the service interface that we want to make transactional

package x.y.service;

public interface FooService {

	Foo getFoo(String fooName);

	Foo getFoo(String fooName, String barName);

	void insertFoo(Foo foo);

	void updateFoo(Foo foo);

}
// the service interface that we want to make transactional

package x.y.service

interface FooService {

	fun getFoo(fooName: String): Foo

	fun getFoo(fooName: String, barName: String): Foo

	fun insertFoo(foo: Foo)

	fun updateFoo(foo: Foo)
}

以下示例显示了上述接口的实现

  • Java

  • Kotlin

package x.y.service;

public class DefaultFooService implements FooService {

	@Override
	public Foo getFoo(String fooName) {
		// ...
	}

	@Override
	public Foo getFoo(String fooName, String barName) {
		// ...
	}

	@Override
	public void insertFoo(Foo foo) {
		// ...
	}

	@Override
	public void updateFoo(Foo foo) {
		// ...
	}
}
package x.y.service

class DefaultFooService : FooService {

	override fun getFoo(fooName: String): Foo {
		// ...
	}

	override fun getFoo(fooName: String, barName: String): Foo {
		// ...
	}

	override fun insertFoo(foo: Foo) {
		// ...
	}

	override fun updateFoo(foo: Foo) {
		// ...
	}
}

假设 FooService 接口的前两个方法 getFoo(String)getFoo(String, String) 必须在具有只读语义的事务上下文中运行,而其他方法 insertFoo(Foo)updateFoo(Foo) 必须在具有读写语义的事务上下文中运行。以下配置在接下来的几段中详细解释

<!-- from the file 'context.xml' -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx
		https://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/aop
		https://www.springframework.org/schema/aop/spring-aop.xsd">

	<!-- this is the service object that we want to make transactional -->
	<bean id="fooService" class="x.y.service.DefaultFooService"/>

	<!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<!-- the transactional semantics... -->
		<tx:attributes>
			<!-- all methods starting with 'get' are read-only -->
			<tx:method name="get*" read-only="true"/>
			<!-- other methods use the default transaction settings (see below) -->
			<tx:method name="*"/>
		</tx:attributes>
	</tx:advice>

	<!-- ensure that the above transactional advice runs for any execution
		of an operation defined by the FooService interface -->
	<aop:config>
		<aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
	</aop:config>

	<!-- don't forget the DataSource -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@rj-t42:1521:elvis"/>
		<property name="username" value="scott"/>
		<property name="password" value="tiger"/>
	</bean>

	<!-- similarly, don't forget the TransactionManager -->
	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>

	<!-- other <bean/> definitions here -->

</beans>

检查上述配置。它假设您希望使服务对象(fooService bean)具有事务性。要应用的事务语义封装在 <tx:advice/> 定义中。<tx:advice/> 定义表示“所有以 get 开头的方法都在只读事务的上下文中运行,所有其他方法都以默认事务语义运行”。<tx:advice/> 标签的 transaction-manager 属性设置为将驱动事务的 TransactionManager bean 的名称(在本例中为 txManager bean)。

如果希望连接的 TransactionManager bean 的名称为 transactionManager,则可以省略事务建议(<tx:advice/>)中的 transaction-manager 属性。如果希望连接的 TransactionManager bean 具有任何其他名称,则必须显式使用 transaction-manager 属性,如上例所示。

<aop:config/> 定义确保 txAdvice bean 定义的事务建议在程序的适当点运行。首先,您定义一个匹配 FooService 接口(fooServiceOperation)中定义的任何操作执行的切入点。然后,您通过使用 Advisor 将切入点与 txAdvice 相关联。结果表明,在执行 fooServiceOperation 时,将运行 txAdvice 定义的建议。

<aop:pointcut/> 元素中定义的表达式是 AspectJ 切入点表达式。有关 Spring 中切入点表达式的更多详细信息,请参阅AOP 部分

一个常见的需求是使整个服务层具有事务性。最好的方法是更改切入点表达式以匹配服务层中的任何操作。以下示例显示了如何做到这一点

<aop:config>
	<aop:pointcut id="fooServiceMethods" expression="execution(* x.y.service.*.*(..))"/>
	<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceMethods"/>
</aop:config>
在前面的示例中,假定所有服务接口都定义在 x.y.service 包中。有关更多详细信息,请参阅AOP 部分

现在我们已经分析了配置,您可能会问自己,“所有这些配置到底做了什么?”

前面显示的配置用于在从 fooService bean 定义创建的对象周围创建一个事务代理。代理配置有事务建议,因此,当在代理上调用适当的方法时,事务会根据与该方法关联的事务配置而启动、挂起、标记为只读等等。考虑以下测试驱动前面所示配置的程序

  • Java

  • Kotlin

public final class Boot {

	public static void main(final String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
		FooService fooService = ctx.getBean(FooService.class);
		fooService.insertFoo(new Foo());
	}
}
import org.springframework.beans.factory.getBean

fun main() {
	val ctx = ClassPathXmlApplicationContext("context.xml")
	val fooService = ctx.getBean<FooService>("fooService")
	fooService.insertFoo(Foo())
}

运行上述程序后输出应类似于以下内容(为清晰起见,已截断 DefaultFooService 类的 insertFoo(..) 方法抛出的 UnsupportedOperationException 的 Log4J 输出和堆栈跟踪)

<!-- the Spring container is starting up... -->
[AspectJInvocationContextExposingAdvisorAutoProxyCreator] - Creating implicit proxy for bean 'fooService' with 0 common interceptors and 1 specific interceptors

<!-- the DefaultFooService is actually proxied -->
[JdkDynamicAopProxy] - Creating JDK dynamic proxy for [x.y.service.DefaultFooService]

<!-- ... the insertFoo(..) method is now being invoked on the proxy -->
[TransactionInterceptor] - Getting transaction for x.y.service.FooService.insertFoo

<!-- the transactional advice kicks in here... -->
[DataSourceTransactionManager] - Creating new transaction with name [x.y.service.FooService.insertFoo]
[DataSourceTransactionManager] - Acquired Connection [org.apache.commons.dbcp.PoolableConnection@a53de4] for JDBC transaction

<!-- the insertFoo(..) method from DefaultFooService throws an exception... -->
[RuleBasedTransactionAttribute] - Applying rules to determine whether transaction should rollback on java.lang.UnsupportedOperationException
[TransactionInterceptor] - Invoking rollback for transaction on x.y.service.FooService.insertFoo due to throwable [java.lang.UnsupportedOperationException]

<!-- and the transaction is rolled back (by default, RuntimeException instances cause rollback) -->
[DataSourceTransactionManager] - Rolling back JDBC transaction on Connection [org.apache.commons.dbcp.PoolableConnection@a53de4]
[DataSourceTransactionManager] - Releasing JDBC Connection after transaction
[DataSourceUtils] - Returning JDBC Connection to DataSource

Exception in thread "main" java.lang.UnsupportedOperationException at x.y.service.DefaultFooService.insertFoo(DefaultFooService.java:14)
<!-- AOP infrastructure stack trace elements removed for clarity -->
at $Proxy0.insertFoo(Unknown Source)
at Boot.main(Boot.java:11)

要使用反应式事务管理,代码必须使用反应式类型。

Spring Framework 使用 ReactiveAdapterRegistry 来确定方法返回类型是否是反应式类型。

以下列表显示了先前使用的 FooService 的修改版本,但这次代码使用了反应式类型

  • Java

  • Kotlin

// the reactive service interface that we want to make transactional

package x.y.service;

public interface FooService {

	Flux<Foo> getFoo(String fooName);

	Publisher<Foo> getFoo(String fooName, String barName);

	Mono<Void> insertFoo(Foo foo);

	Mono<Void> updateFoo(Foo foo);

}
// the reactive service interface that we want to make transactional

package x.y.service

interface FooService {

	fun getFoo(fooName: String): Flow<Foo>

	fun getFoo(fooName: String, barName: String): Publisher<Foo>

	fun insertFoo(foo: Foo) : Mono<Void>

	fun updateFoo(foo: Foo) : Mono<Void>
}

以下示例显示了上述接口的实现

  • Java

  • Kotlin

package x.y.service;

public class DefaultFooService implements FooService {

	@Override
	public Flux<Foo> getFoo(String fooName) {
		// ...
	}

	@Override
	public Publisher<Foo> getFoo(String fooName, String barName) {
		// ...
	}

	@Override
	public Mono<Void> insertFoo(Foo foo) {
		// ...
	}

	@Override
	public Mono<Void> updateFoo(Foo foo) {
		// ...
	}
}
package x.y.service

class DefaultFooService : FooService {

	override fun getFoo(fooName: String): Flow<Foo> {
		// ...
	}

	override fun getFoo(fooName: String, barName: String): Publisher<Foo> {
		// ...
	}

	override fun insertFoo(foo: Foo): Mono<Void> {
		// ...
	}

	override fun updateFoo(foo: Foo): Mono<Void> {
		// ...
	}
}

命令式和反应式事务管理在事务边界和事务属性定义方面共享相同的语义。命令式事务和反应式事务之间的主要区别在于后者的延迟特性。TransactionInterceptor 用事务操作符装饰返回的反应式类型,以开始和清理事务。因此,调用事务性反应式方法将实际的事务管理推迟到激活反应式类型处理的订阅类型。

反应式事务管理的另一个方面与数据逃逸有关,这是编程模型的自然结果。

命令式事务的方法返回值在方法成功终止时从事务方法返回,这样部分计算结果就不会逃逸方法闭包。

反应式事务方法返回一个反应式包装类型,它表示一个计算序列以及开始和完成计算的承诺。

当事务正在进行但尚未完成时,Publisher 可以发出数据。因此,依赖于整个事务成功完成的方法需要确保完成并在调用代码中缓冲结果。

© . This site is unofficial and not affiliated with VMware.