好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring 事务事件监控及实现原理解析

前面我们讲到了spring在进行 事务 逻辑织入的时候,无论是事务开始,提交或者回滚,都会触发相应的事务事件。本文首先会使用实例进行讲解spring事务事件是如何使用的,然后会讲解这种使用方式的实现原理。

1. 示例

对于事务事件,spring提供了一个注解@transactioneventlistener,将这个注解标注在某个方法上,那么就将这个方法声明为了一个事务事件处理器,而具体的事件类型则是由transactionaleventlistener.phase属性进行定义的。如下是transactionaleventlistener的声明:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@target ({elementtype.method, elementtype.annotation_type})

@retention (retentionpolicy.runtime)

@documented

@eventlistener

public @interface transactionaleventlistener {

   // 指定当前标注方法处理事务的类型

     transactionphase phase() default transactionphase.after_commit;

   // 用于指定当前方法如果没有事务,是否执行相应的事务事件监听器

     boolean fallbackexecution() default false ;

   // 与classes属性一样,指定了当前事件传入的参数类型,指定了这个参数之后就可以在监听方法上

   // 直接什么一个这个参数了

     @aliasfor (annotation = eventlistener. class , attribute = "classes" )

     class <?>[] value() default {};

   // 作用于value属性一样,用于指定当前监听方法的参数类型

     @aliasfor (annotation = eventlistener. class , attribute = "classes" )

     class <?>[] classes() default {};

   // 这个属性使用spring expression language对目标类和方法进行匹配,对于不匹配的方法将会过滤掉

     string condition() default "" ;

}

关于这里的classes属性需要说明一下,如果指定了classes属性,那么当前监听方法的参数类型就可以直接使用所发布的事件的参数类型,如果没有指定,那么这里监听的参数类型可以使用两种:applicationevent和payloadapplicationevent。对于applicationevent类型的参数,可以通过其getsource()方法获取发布的事件参数,只不过其返回值是一个object类型的,如果想获取具体的类型还需要进行强转;对于payloadapplicationevent类型,其可以指定一个泛型参数,该泛型参数必须与发布的事件的参数类型一致,这样就可以通过其getpayload()方法获取事务事件发布的数据了。关于上述属性中的transactionphase,其可以取如下几个类型的值:

?

1

2

3

4

5

6

7

8

9

10

public enum transactionphase {

   // 指定目标方法在事务commit之前执行

     before_commit,

   // 指定目标方法在事务commit之后执行

     after_commit,

   // 指定目标方法在事务rollback之后执行

     after_rollback,

   // 指定目标方法在事务完成时执行,这里的完成是指无论事务是成功提交还是事务回滚了

     after_completion

}

这里我们假设数据库有一个user表,对应的有一个userservice和user的model,用于往该表中插入数据,并且插入动作时使用注解标注目标方法。如下是这几个类的声明:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

public class user {

  private long id;

  private string name;

  private int age;

  // getter and setter...

}

@service

@transactional

public class userserviceimpl implements userservice {

  @autowired

  private jdbctemplate jdbctemplate;

  @autowired

  private applicationeventpublisher publisher;

  @override

  public void insert(user user) {

   jdbctemplate.update( "insert into user (id, name, age) value (?, ?, ?)" ,

     user.getid(), user.getname(), user.getage());

   publisher.publishevent(user);

  }

}

上述代码中有一点需要注意的是,对于需要 监控 事务事件的方法,在目标方法执行的时候需要使用

applicationeventpublisher发布相应的事件消息。如下是对上述消息进行监控的程序:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@component

public class usertransactioneventlistener {

  @transactionaleventlistener (phase = transactionphase.before_commit)

  public void beforecommit(payloadapplicationevent<user> event) {

   system.out.println( "before commit, id: " + event.getpayload().getid());

  }

  @transactionaleventlistener (phase = transactionphase.after_commit)

  public void aftercommit(payloadapplicationevent<user> event) {

   system.out.println( "after commit, id: " + event.getpayload().getid());

  }

  @transactionaleventlistener (phase = transactionphase.after_completion)

  public void aftercompletion(payloadapplicationevent<user> event) {

   system.out.println( "after completion, id: " + event.getpayload().getid());

  }

  @transactionaleventlistener (phase = transactionphase.after_rollback)

  public void afterrollback(payloadapplicationevent<user> event) {

   system.out.println( "after rollback, id: " + event.getpayload().getid());

  }

}

这里对于事件的监控,只需要在监听方法上添加@transactionaleventlistener注解即可。这里需要注意的一个问题,在实际使用过程中,对于监听的事务事件,需要使用其他的参数进行事件的过滤,因为这里的监听还是会监听所有事件参数为user类型的事务,而无论其是哪个位置发出来的。如果需要对事件进行过滤,这里可以封装一个userevent对象,其内保存一个类似eventtype的属性和一个user对象,这样在发布消息的时候就可以指定eventtype属性,而在监听消息的时候判断当前方法监听的事件对象的eventtype是否为目标type,如果是,则对其进行处理,否则直接略过。下面是上述程序的xml文件配置和驱动程序:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

<bean id= "datasource" class = "org.apache测试数据mons.dbcp.basicdatasource" >

   <property name= "url" value= "jdbc:mysql://localhost/test?useunicode=true" />

   <property name= "driverclassname" value= "com.mysql.jdbc.driver" />

   <property name= "username" value= "******" />

   <property name= "password" value= "******" />

</bean>

 

<bean id= "jdbctemplate" class = "org.springframework.jdbc.core.jdbctemplate" >

   <property name= "datasource" ref= "datasource" />

</bean>

 

<bean id= "transactionmanager" class = "org.springframework.jdbc.datasource.datasourcetransactionmanager" >

   <property name= "datasource" ref= "datasource" />

</bean>

 

<context:component-scan base- package = "com.transaction" />

<tx:annotation-driven/>

public class transactionapp {

  @test

  public void testtransaction() {

   applicationcontext ac = new classpathxmlapplicationcontext( "applicationcontext.xml" );

   userservice userservice = context.getbean(userservice. class );

   user user = getuser();

   userservice.insert(user);

  }

 

  private user getuser() {

   int id = new random()

    .nextint( 1000000 );

   user user = new user();

   user.setid(id);

   user.setname( "mary" );

   user.setage( 27 );

   return user;

  }

}

运行上述程序,其执行结果如下:

?

1

2

3

before commit, id: 935052

after commit, id: 935052

after completion, id: 935052

可以看到,这里确实成功监听了目标程序的相关事务行为。

2. 实现原理

关于事务的实现原理,这里其实是比较简单的,在前面的文章中,我们讲解到,spring对事务监控的处理逻辑在transactionsynchronization中,如下是该接口的声明:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

public interface transactionsynchronization extends flushable {

 

   // 在当前事务挂起时执行

     default void suspend() {

     }

 

   // 在当前事务重新加载时执行

     default void resume() {

     }

 

   // 在当前数据刷新到数据库时执行

     default void flush() {

     }

 

   // 在当前事务commit之前执行

     default void beforecommit( boolean readonly) {

     }

 

   // 在当前事务completion之前执行

     default void beforecompletion() {

     }

  

   // 在当前事务commit之后实质性

     default void aftercommit() {

     }

 

   // 在当前事务completion之后执行

     default void aftercompletion( int status) {

     }

}

很明显,这里的transactionsynchronization接口只是抽象了一些行为,用于事务事件发生时触发,这些行为在spring事务中提供了内在支持,即在相应的事务事件时,其会获取当前所有注册的transactionsynchronization对象,然后调用其相应的方法。那么这里transactionsynchronization对象的注册点对于我们了解事务事件触发有至关重要的作用了。这里我们首先回到事务标签的解析处,在前面讲解事务标签解析时,我们讲到spring会注册一个transactionaleventlistenerfactory类型的bean到spring容器中,这里关于标签的解析读者可以阅读本人前面的文章spring事务用法示例与实现原理。这里注册的transactionaleventlistenerfactory实现了eventlistenerfactory接口,这个接口的主要作用是先判断目标方法是否是某个监听器的类型,然后为目标方法生成一个监听器,其会在某个bean初始化之后由spring调用其方法用于生成监听器。如下是该类的实现:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

ublic class transactionaleventlistenerfactory implements eventlistenerfactory, ordered {

 

   // 指定当前监听器的顺序

   private int order = 50 ;

 

   public void setorder( int order) {

     this .order = order;

   }

 

   @override

   public int getorder() {

     return this .order;

   }

 

 

   // 指定目标方法是否是所支持的监听器的类型,这里的判断逻辑就是如果目标方法上包含有

   // transactionaleventlistener注解,则说明其是一个事务事件监听器

   @override

   public boolean supportsmethod(method method) {

     return (annotationutils.findannotation(method, transactionaleventlistener. class ) != null );

   }

 

   // 为目标方法生成一个事务事件监听器,这里applicationlistenermethodtransactionaladapter实现了

   // applicationevent接口

   @override

   public applicationlistener<?> createapplicationlistener(string beanname, class <?> type, method method) {

     return new applicationlistenermethodtransactionaladapter(beanname, type, method);

   }

 

}

这里关于事务事件监听的逻辑其实已经比较清楚了。applicationlistenermethodtransactionaladapter本质上是实现了applicationlistener接口的,也就是说,其是spring的一个事件监听器,这也就是为什么进行事务处理时需要使用applicationeventpublisher.publish()方法发布一下当前事务的事件。

applicationlistenermethodtransactionaladapter在监听到发布的事件之后会生成一个transactionsynchronization对象,并且将该对象注册到当前事务逻辑中,如下是监听事务事件的处理逻辑:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

@override

public void onapplicationevent(applicationevent event) {

   // 如果当前transactionmanager已经配置开启事务事件监听,

   // 此时才会注册transactionsynchronization对象

   if (transactionsynchronizationmanager.issynchronizationactive()) {

     // 通过当前事务事件发布的参数,创建一个transactionsynchronization对象

     transactionsynchronization transactionsynchronization =

       createtransactionsynchronization(event);

     // 注册transactionsynchronization对象到transactionmanager中

     transactionsynchronizationmanager

       .registersynchronization(transactionsynchronization);

   } else if ( this .annotation.fallbackexecution()) {

     // 如果当前transactionmanager没有开启事务事件处理,但是当前事务监听方法中配置了

     // fallbackexecution属性为true,说明其需要对当前事务事件进行监听,无论其是否有事务

     if ( this .annotation.phase() == transactionphase.after_rollback

       && logger.iswarnenabled()) {

       logger.warn( "processing "

             + event + " as a fallback execution on after_rollback phase" );

     }

     processevent(event);

   } else {

     // 走到这里说明当前是不需要事务事件处理的,因而直接略过

     if (logger.isdebugenabled()) {

       logger.debug( "no transaction is active - skipping " + event);

     }

   }

}

这里需要说明的是,上述annotation属性就是在事务监听方法上解析的transactionaleventlistener注解中配置的属性。可以看到,对于事务事件的处理,这里创建了一个transactionsynchronization对象,其实主要的处理逻辑就是在返回的这个对象中,而createtransactionsynchronization()方法内部只是创建了一个transactionsynchronizationeventadapter对象就返回了。这里我们直接看该对象的源码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

private static class transactionsynchronizationeventadapter

     extends transactionsynchronizationadapter {

 

   private final applicationlistenermethodadapter listener;

   private final applicationevent event;

   private final transactionphase phase;

 

   public transactionsynchronizationeventadapter(applicationlistenermethodadapter

     listener, applicationevent event, transactionphase phase) {

     this .listener = listener;

     this .event = event;

     this .phase = phase;

   }

 

   @override

   public int getorder() {

     return this .listener.getorder();

   }

 

   // 在目标方法配置的phase属性为before_commit时,处理before commit事件

   public void beforecommit( boolean readonly) {

     if ( this .phase == transactionphase.before_commit) {

       processevent();

     }

   }

 

   // 这里对于after completion事件的处理,虽然分为了三个if分支,但是实际上都是执行的processevent()

   // 方法,因为after completion事件是事务事件中一定会执行的,因而这里对于commit,

   // rollback和completion事件都在当前方法中处理也是没问题的

   public void aftercompletion( int status) {

     if ( this .phase == transactionphase.after_commit && status == status_committed) {

       processevent();

     } else if ( this .phase == transactionphase.after_rollback

           && status == status_rolled_back) {

       processevent();

     } else if ( this .phase == transactionphase.after_completion) {

       processevent();

     }

   }

 

   // 执行事务事件

   protected void processevent() {

     this .listener.processevent( this .event);

   }

}

可以看到,对于事务事件的处理,最终都是委托给了applicationlistenermethodadapter.processevent()方法进行的。如下是该方法的源码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

public void processevent(applicationevent event) {

   // 处理事务事件的相关参数,这里主要是判断transactionaleventlistener注解中是否配置了value

   // 或classes属性,如果配置了,则将方法参数转换为该指定类型传给监听的方法;如果没有配置,则判断

   // 目标方法是applicationevent类型还是payloadapplicationevent类型,是则转换为该类型传入

   object[] args = resolvearguments(event);

   // 这里主要是获取transactionaleventlistener注解中的condition属性,然后通过

   // spring expression language将其与目标类和方法进行匹配

   if (shouldhandle(event, args)) {

     // 通过处理得到的参数借助于反射调用事务监听方法

     object result = doinvoke(args);

     if (result != null ) {

       // 对方法的返回值进行处理

       handleresult(result);

     } else {

       logger.trace( "no result object given - no result to handle" );

     }

   }

}

 

// 处理事务监听方法的参数

protected object[] resolvearguments(applicationevent event) {

   // 获取发布事务事件时传入的参数类型

   resolvabletype declaredeventtype = getresolvabletype(event);

   if (declaredeventtype == null ) {

     return null ;

   }

  

   // 如果事务监听方法的参数个数为0,则直接返回

   if ( this .method.getparametercount() == 0 ) {

     return new object[ 0 ];

   }

  

   // 如果事务监听方法的参数不为applicationevent或payloadapplicationevent,则直接将发布事务

   // 事件时传入的参数当做事务监听方法的参数传入。从这里可以看出,如果事务监听方法的参数不是

   // applicationevent或payloadapplicationevent类型,那么其参数必须只能有一个,并且这个

   // 参数必须与发布事务事件时传入的参数一致

   class <?> eventclass = declaredeventtype.getrawclass();

   if ((eventclass == null || !applicationevent. class .isassignablefrom(eventclass)) &&

     event instanceof payloadapplicationevent) {

     return new object[] {((payloadapplicationevent) event).getpayload()};

   } else {

     // 如果参数类型为applicationevent或payloadapplicationevent,则直接将其传入事务事件方法

     return new object[] {event};

   }

}

 

// 判断事务事件方法方法是否需要进行事务事件处理

private boolean shouldhandle(applicationevent event, @nullable object[] args) {

   if (args == null ) {

     return false ;

   }

   string condition = getcondition();

   if (stringutils.hastext(condition)) {

     assert .notnull( this .evaluator, "eventexpressionevaluator must no be null" );

     evaluationcontext evaluationcontext = this .evaluator.createevaluationcontext(

       event, this .targetclass, this .method, args, this .applicationcontext);

     return this .evaluator.condition(condition, this .methodkey, evaluationcontext);

   }

   return true ;

}

 

// 对事务事件方法的返回值进行处理,这里的处理方式主要是将其作为一个事件继续发布出去,这样就可以在

// 一个统一的位置对事务事件的返回值进行处理

protected void handleresult(object result) {

   // 如果返回值是数组类型,则对数组元素一个一个进行发布

   if (result.getclass().isarray()) {

     object[] events = objectutils.toobjectarray(result);

     for (object event : events) {

       publishevent(event);

     }

   } else if (result instanceof collection<?>) {

     // 如果返回值是集合类型,则对集合进行遍历,并且发布集合中的每个元素

     collection<?> events = (collection<?>) result;

     for (object event : events) {

       publishevent(event);

     }

   } else {

     // 如果返回值是一个对象,则直接将其进行发布

     publishevent(result);

   }

}

对于事务事件的处理,总结而言,就是为每个事务事件监听方法创建了一个transactionsynchronizationeventadapter对象,通过该对象在发布事务事件的时候,会在当前线程中注册该对象,这样就可以保证每个线程每个监听器中只会对应一个transactionsynchronizationeventadapter对象。在spring进行事务事件的时候会调用该对象对应的监听方法,从而达到对事务事件进行监听的目的。

3. 小结

本文首先对事务事件监听程序的使用方式进行了讲解,然后在源码层面讲解了spring事务监听器是如何实现的。在spring事务监听器使用过程中,需要注意的是要对当前接收到的事件类型进行判断,因为不同的事务可能会发布同样的消息对象过来。

总结

以上所述是小编给大家介绍的spring 事务事件监控及实现原理,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://my.oschina.net/zhangxufeng/blog/1976076

查看更多关于Spring 事务事件监控及实现原理解析的详细内容...

  阅读:10次