spring中的异步事件

场景介绍

如何实现用户登录后给用户发送消息

分析过程

 这里用到了spring的事件机制,事件机制其实是观察者模式在spring中的体现。用户登录是事件源 , 触发了给用户发消息这一事件

实现过程

定义事件类型

import org.springframework.context.ApplicationEvent;

public class ContentEvent  extends ApplicationEvent  {

    public ContentEvent(Object source) {
        super(source);
    }


    private static final long serialVersionUID = 1L;


}

定义一个事件监听器

import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class LisiListener  implements ApplicationListener<ContentEvent>{

    @Async  
    @Override
    public void onApplicationEvent(ContentEvent event) {
         System.out.println("李四收到了新的内容: ***********************" + event.getSource());  
    }

}

spring配置文件中增加如下内容

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

    <!-- 任务调度器 -->  
    <task:scheduler id="scheduler" pool-size="10"/>  

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

    <!--开启注解调度支持 @Async @Scheduled-->  
    <task:annotation-driven executor="executor" scheduler="scheduler" proxy-target-class="true"/> 

测试


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:application-context.xml"})
public class TestAsyncEvent {


    @Autowired  
    private ApplicationContext applicationContext;  


    @Test  
    public void testPublishEvent() {  
        applicationContext.publishEvent(new ContentEvent(" martin  来了"));  
        System.out.println("等待事件完成!!!!!");

    }  
}

测试结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值