浅谈Spring事件机制

一、同步事件和异步事件

同步事件:在一个线程里,按顺序执行业务,做完一件事再去做下一件事。

异步事件:在一个线程里,做一个事的同事,可以另起一个新的线程执行另一件事,这样两件事可以同时执行。

用一个例子来解释同步事件和异步事件的使用场景,有时候一段完整的代码逻辑,可能分为几部分,拿最常见的注册来说,假设完整流程是:

1、点击注册;

2、检验信息并存库;

3、发送邮件;

4、返回给用户。

代码这么写是正确,但不是最好的,缺点如下:

① 逻辑复杂,业务耦合。

② 效率低

加入2和3分别需要1秒,那么用户在点击注册2秒后才能有结果。

同步事件可以帮我们解决①问题,我们把发邮件的方法独立处理,放到事件里执行,这样注册的这个方法就只做两步,完成之后发布一个事件去执行3,可以很好的解决业务耦合的问题。

异步事件可以完美解决以上两个问题,注册方法执行2操作,执行之后发布一个异步事件,另起一个线程执行3操作,注册方法所在的线程可直接返回给用户,这样不仅实现了业务解耦还提高了效率,用户点击注册,1秒后就能看到响应。

二、Spring事件机制

Spring事件发送监听涉及三个部分

1、ApplicationEvent

表示事件本身,自定义事件需要继承该类,可以用来传递数据,比如上述发邮件操作

2、ApplicationEventPublishAware

事件发送器,通过实现这个接口,来触发事件

3、ApplicationListener

事件监听器接口,事件的业务逻辑封装在监听器里面

三、异步事件机制模拟实现注册

配置文件和注解两种方式。

1、配置文件方式

TestEvent

public class TestEvent extends ApplicationEvent {

    private TestParam source;

    public TestEvent(TestParam source) {
        super(source);
        this.source = source;
    }
}

@Data
public class TestParam {
    private String email;
}

 TestListener

@Component
public class TestListener implements ApplicationListener<TestEvent> {

    @Override
    public void onApplicationEvent(TestEvent testEvent) {

        TestParam param = (TestParam) testEvent.getSource();
        System.out.println(".......开始.......");
        System.out.println("发送邮件:"+param.getEmail());
        System.out.println(".......结束.....");
    }
}

TestPublish

@Component
public class TestPublish implements ApplicationEventPublisherAware {

    private static ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        TestPublish.applicationEventPublisher = applicationEventPublisher;
    }

    public static void  publishEvent(ApplicationEvent communityArticleEvent) {
        applicationEventPublisher.publishEvent(communityArticleEvent);
    }
}

spring-context.xml

<bean id="applicationEventAsyncMulticaster" class="org.springframework.context.event.SimpleApplicationEventMulticaster">
        <property name="taskExecutor">
            <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
                <property name="corePoolSize" value="5"/>
                <property name="keepAliveSeconds" value="3000"/>
                <property name="maxPoolSize" value="50"/>
                <property name="queueCapacity" value="200"/>
            </bean>
        </property>
    </bean>

 注意:如果加<propery name="taskExecutor",则使用异步方式执行,否则为同步方式。

2、注解方式

使用@Async需要在配置文件添加一下支持,线程池也是需要配置一下的

<!-- 开启@AspectJ AOP代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>

<!-- 任务执行器 -->
<task:executor id="executor" pool-size="10"/>

<!--开启注解调度支持 @Async -->
<task:annotation-driven executor="executor" proxy-target-class="true"/>
TestListener中在方法中添加@Async
@Component
public class TestListener implements ApplicationListener<TestEvent> {

    @Async
    @Override
    public void onApplicationEvent(TestEvent testEvent) {

        TestParam param = (TestParam) testEvent.getSource();
        System.out.println(".......开始.......");
        System.out.println("发送邮件:"+param.getEmail());
        System.out.println(".......结束.....");
    }
}

Listener其实还可以做得更彻底一点,使用注解@EventListener可代替实现ApplicationListener,原理是通过扫描这个注解来创建监听器并自动添加到ApplicationContext中。

TestListenerHandler

@Component
public class TestEventHandler {

    @Async
    @EventListener
    public void handleTestEvent(TestEvent testEvent) {

        TestParam param = (TestParam) testEvent.getSource();
        System.out.println(".......开始.......");
        System.out.println("发送邮件:"+param.getEmail());
        System.out.println(".......结束.....");
    }
}

四、总结

使用Spring事件机制能很好地帮助我们消除不同业务间的耦合关系,也可以提高执行效率,应该根据业务场景灵活选择。

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哪 吒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值