前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring事务监听机制---使用@TransactionalEventListener处理数据库事务提交成功后再执行操作(附:Spring4.2新特性讲解)【享学Spring】

Spring事务监听机制---使用@TransactionalEventListener处理数据库事务提交成功后再执行操作(附:Spring4.2新特性讲解)【享学Spring】

作者头像
YourBatman
发布2019-09-03 16:06:09
8.9K0
发布2019-09-03 16:06:09
举报
文章被收录于专栏:BAT的乌托邦BAT的乌托邦
前言

从标题就可以看出,本篇文章内容既和Spring的事件/监听机制有关,同时还和Spring事务以及Spring事务同步机制有关。

为了给这篇文章铺好路,建议可以先了解下:

Spring事件监听机制:

【小家Spring】从Spring中的(ApplicationEvent)事件驱动机制出发,聊聊【观察者模式】【监听者模式】【发布订阅模式】【消息队列MQ】【EventSourcing】…

Spring事务同步机制:

【小家Spring】Spring是如何保证同一事务获取同一个Connection的?使用Spring的事务同步机制解决:数据库刚插入的记录却查询不到的问题

在项目开发过程中,我们不乏会有这样的诉求:需要在执行完数据库操作后,发送消息(比如短信、邮件、微信通知等)来执行其它的操作,而这些并不是主干业务,所以一般会放在异步线程里去执行~

关于这么执行的情况,上篇文章大篇幅解释了:这样可能会出现业界经典的事务提交成功后进行异步操作问题。关于问题的解决,Spring它非常友好的提供了两种解决方案来处理:

  1. 事务同步管理器TransactionSynchronizationManager
  2. @TransactionalEventListener注解(需要Spring4.2+

办法1在上篇文章,那么本文将叙述通过方式二,来更加优雅的处理Spring事务同步问题。

@TransactionalEventListener

首先不得不说,从命名中就可以直接看出,它就是个EventListener

Spring4.2+,有一种叫做@TransactionEventListener的方式,能够 控制 在事务的时候Event事件的处理方式。

我们知道,Spring的事件监听机制(发布订阅模型)实际上并不是异步的(默认情况下),而是同步的来将代码进行解耦。而@TransactionEventListener仍是通过这种方式,只不过加入了回调的方式来解决,这样就能够在事务进行Commited,Rollback…等的时候才会去进行Event的处理,达到事务同步的目的

Demo演示

基于上一篇博文的Demo案例,本文用@TransactionEventListener的方式进行改造如下:

@Slf4j
@Service
public class HelloServiceImpl implements HelloService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Transactional
    @Override
    public Object hello(Integer id) {
        // 向数据库插入一条记录
        String sql = "insert into user (id,name,age) values (" + id + ",'fsx',21)";
        jdbcTemplate.update(sql);

        // 发布一个自定义的事件~~~
        applicationEventPublisher.publishEvent(new MyAfterTransactionEvent("我是和事务相关的事件,请事务提交后执行我~~~", id));
        return "service hello";
    }

    @Slf4j
    @Component
    private static class MyTransactionListener {
        @Autowired
        private JdbcTemplate jdbcTemplate;

        @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
        private void onHelloEvent(HelloServiceImpl.MyAfterTransactionEvent event) {
            Object source = event.getSource();
            Integer id = event.getId();

            String query = "select count(1) from user where id = " + id;
            Integer count = jdbcTemplate.queryForObject(query, Integer.class);
            
            // 可以看到 这里的count是1  它肯定是在上面事务提交之后才会执行的
            log.info(source + ":" + count.toString()); //我是和事务相关的事件,请事务提交后执行我~~~:1
        }
    }


    // 定一个事件,继承自ApplicationEvent 
    private static class MyAfterTransactionEvent extends ApplicationEvent {

        private Integer id;

        public MyAfterTransactionEvent(Object source, Integer id) {
            super(source);
            this.id = id;
        }

        public Integer getId() {
            return id;
        }
    }
}

首先确认,通过@TransactionalEventListener注解的方式,是完全可以处理这种事务问题的。

接下来先看看这个注解本身,有哪些属性是我们可用、可控的:

// @since 4.2  显然,注解的方式提供得还是挺晚的,而API的方式第一个版本就已经提供了
// 另外最重要的是,它头上有一个注解:`@EventListener`  so  
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener //有类似于注解继承的效果
public @interface TransactionalEventListener {
	// 这个注解取值有:BEFORE_COMMIT、AFTER_COMMIT、AFTER_ROLLBACK、AFTER_COMPLETION
	// 各个值都代表什么意思表达什么功能,非常清晰~
	// 需要注意的是:AFTER_COMMIT + AFTER_COMPLETION是可以同时生效的
	// AFTER_ROLLBACK + AFTER_COMPLETION是可以同时生效的
	TransactionPhase phase() default TransactionPhase.AFTER_COMMIT;

	// 若没有事务的时候,对应的event是否已经执行  默认值为false表示  没事务就不执行了
	boolean fallbackExecution() default false;

	// 这里巧妙的用到了@AliasFor的能力,放到了@EventListener身上
	// 注意:一般我建议都需要指定此值,否则默认可以处理所有类型的事件  范围太广了
	@AliasFor(annotation = EventListener.class, attribute = "classes")
	Class<?>[] value() default {};
	@AliasFor(annotation = EventListener.class, attribute = "classes")
	Class<?>[] classes() default {};
	
	String condition() default "";
}

可以看到它实际上相当于在@EventListener的基础上扩展了两个属性,来对事务针对性的处理。

根据前面的Spring事件监听机制的理论知识得知:它的注册原理显然也在EventListenerMethodProcessor中,只不过它使用的是TransactionalEventListenerFactory最终来生成一个Adapter适配器:

public class TransactionalEventListenerFactory implements EventListenerFactory, Ordered {
	private int order = 50; // 执行时机还是比较早的~~~(默认的工厂是最低优先级)
	
	// 显然这个工厂只会生成标注有此注解的handler~~~
	@Override
	public boolean supportsMethod(Method method) {
		return AnnotatedElementUtils.hasAnnotation(method, TransactionalEventListener.class);
	}

	// 这里使用的是ApplicationListenerMethodTransactionalAdapter,而非ApplicationListenerMethodAdapter
	// 虽然ApplicationListenerMethodTransactionalAdapter是它的子类
	@Override
	public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {
		return new ApplicationListenerMethodTransactionalAdapter(beanName, type, method);
	}
}

通过这个工厂,会把每个标注有@TransactionalEventListener注解的方法最终都包装成一个ApplicationListenerMethodTransactionalAdapter,它是一个ApplicationListener,最终注册进事件发射器的容器里面


ApplicationListenerMethodTransactionalAdapter

它是包装@TransactionalEventListener的适配器,继承自ApplicationListenerMethodAdapter~

// @since 4.2
class ApplicationListenerMethodTransactionalAdapter extends ApplicationListenerMethodAdapter {

	private final TransactionalEventListener annotation;

	// 构造函数
	public ApplicationListenerMethodTransactionalAdapter(String beanName, Class<?> targetClass, Method method) {
		// 这一步的初始化交给父类,做了很多事情   强烈建议看看上面推荐的事件/监听的博文
		super(beanName, targetClass, method);

		// 自己个性化的:和事务相关
		TransactionalEventListener ann = AnnotatedElementUtils.findMergedAnnotation(method, TransactionalEventListener.class);
		if (ann == null) {
			throw new IllegalStateException("No TransactionalEventListener annotation found on method: " + method);
		}
		this.annotation = ann;
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		// 若**存在事务**:毫无疑问 就注册一个同步器进去~~
		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
			TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
		}
		// 若fallbackExecution=true,那就是表示即使没有事务  也会执行handler
		else if (this.annotation.fallbackExecution()) {
			if (this.annotation.phase() == TransactionPhase.AFTER_ROLLBACK && logger.isWarnEnabled()) {
				logger.warn("Processing " + event + " as a fallback execution on AFTER_ROLLBACK phase");
			}
			processEvent(event);
		}
		else {
			// No transactional event execution at all
			// 若没有事务,输出一个debug信息,表示这个监听器没有执行~~~~
			if (logger.isDebugEnabled()) {
				logger.debug("No transaction is active - skipping " + event);
			}
		}
	}

	// TransactionSynchronizationEventAdapter是一个内部类,它是一个TransactionSynchronization同步器
	// 此类实现也比较简单,它的order由listener.getOrder();来决定
	private TransactionSynchronization createTransactionSynchronization(ApplicationEvent event) {
		return new TransactionSynchronizationEventAdapter(this, event, this.annotation.phase());
	}


	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;
		}

		// 它的order又监听器本身来决定  
		@Override
		public int getOrder() {
			return this.listener.getOrder();
		}

		// 最终都是委托给了listenner来真正的执行处理  来执行最终处理逻辑(也就是解析classes、condtion、执行方法体等等)
		@Override
		public void beforeCommit(boolean readOnly) {
			if (this.phase == TransactionPhase.BEFORE_COMMIT) {
				processEvent();
			}
		}

		// 此处结合status和phase   判断是否应该执行~~~~
		// 此处小技巧:我们发现TransactionPhase.AFTER_COMMIT也是放在了此处执行的,只是它结合了status进行判断而已~~~
		@Override
		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);
		}
	}
}

从源码里可以看出,其实@TransactionalEventListener的底层实现原理还是事务同步器:TransactionSynchronizationTransactionSynchronizationManager

以上,建立在小伙伴已经知晓了Spring事件/监听机制的基础上,回头看Spring事务的监听机制其实就非常非常的简单了(没有多少新东西)。

至于在平时业务编码中处理Spring的事务同步的时候选择哪种方式呢??我觉得两种方式都是ok的,看各位的喜好了(我个人偏爱注解方式,耦合度低很多并且还可以使用事件链,有时候非常好使)

需要提一句:@TransactionalEventListener@EventListener一样是存在一个加载时机问题的,若你对加载时机有严格要求和把控,建议使用API的方式而非注解方式,避免监听器未被执行而导致逻辑出错~




由于此篇文章出现的类和API大都是Spring4.2开始有的,所以借此机会介绍几个 我认为的 相对比较重要(常用)的Spring4.2的新特性,希望对小伙伴们能有所帮助

Spring4.2新特性(部分)

说明:新特性中有些一看标题就知道什么意思和怎么用的,就不做案例介绍了

1、@Bean能注解在Java8默认方法上了
2、@Import可以引入没任何注解标注的类作为组件了

在这之前,@Import只能导入配置类(注解了@Configuration等的类),现在即使非常普通的javaBean都能被导入进来作为组件了

3、@Configuration配置类上可以使用@Order来按照预期顺序处理了
4、@Resource可以和@Lazy配合使用了(重难点)

之前只能@Autowired@Lazy配合使用来注入多例的代理Bean,现在@Resource也可以了。给出一个范例如下:

@Import(ScopedBean.class) // 使用@Import注入  即使它头上没有任何注解也是ok的
@Configuration
public class Main {

    @Lazy
    @Resource
    ScopedBean bean;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Main.class);

        Main bean = context.getBean(Main.class);

        //如果bean上没有@Lazy注解, 则2个获取的bean是一个实例, 
        //加了@Lazy注解后, 则2次获取的是2个实例
        System.out.println(bean.bean);
        System.out.println(bean.bean);

        context.close();
    }

}

// 多例    
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class ScopedBean {
}

@Lazy注解去掉,其余任何什么都不变:

    @Resource
    ScopedBean bean;
	...
        System.out.println(bean.bean); //com.fsx.maintest.ScopedBean@5fdcaa40
        System.out.println(bean.bean); //com.fsx.maintest.ScopedBean@5e0826e7

可以看到,没有标注@Lazy每次获取Bean都是同一个Bean了。(因为Spring为属性注入值,会立马getBean,所以这个时候@Scope可能达不到你的效果了,使用时需要引起注意~)

主要是为了方便实现Scope代理(或延迟获取, 比如注入时还没初始化等)情况, 也就是当singleton引用prototype时, 就需要@Lazy

5、提供@EventListener注解等相关API

这是本文主要讲述的内容了,当然还有@TransactionalEventListener等API,再提一句:它的condition属性是可以使用SpEL表达式的

6、提供@AliasFor注解

提供@AliasFor注解, 来给注解的属性起别名, 让使用注解时, 更加的容易理解(比如给value属性起别名, 更容易让人理解).

此注解的解析原理非常复杂,后面会做更加详细的讨论,此处先知道怎么用即可

给出如下使用案例作为参考:

@MainBean(beanName = "mainbean")
public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
        String[] beannames = context.getBeanNamesForType(Main.class);

        //当加上@AliasFor时, 输出"mainbean"
        //当去掉@AliasFor注解后, 输出"main"(`main`是默认的beanName生成策略生成的)
        System.out.println(beannames[0]);
        context.close();
    }
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@interface MainBean {
    @AliasFor(annotation = Component.class, attribute = "value")
    String beanName() default "";
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年06月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • @TransactionalEventListener
    • Demo演示
      • ApplicationListenerMethodTransactionalAdapter
        • 1、@Bean能注解在Java8默认方法上了
        • 2、@Import可以引入没任何注解标注的类作为组件了
        • 3、@Configuration配置类上可以使用@Order来按照预期顺序处理了
        • 4、@Resource可以和@Lazy配合使用了(重难点)
        • 5、提供@EventListener注解等相关API
        • 6、提供@AliasFor注解
    • Spring4.2新特性(部分)
    相关产品与服务
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档