spring 事件为bean 与 bean之间传递消息。一个bean处理完了希望其余一个接着处理.这时我们就需要其余的一个bean监听当前bean所发送的事件.

spring事件使用步骤如下:

1.先自定义事件:你的事件需要继承 ApplicationEvent

2.定义事件监听器: 需要实现 ApplicationListener

3.使用容器对事件进行发布

  • 首先定义一个事件
/**
* @Title:
* @Auther: hangyu
* @Date: 2019/3/13
* @Description
* @Version:1.0
*/
public class TestEvent extends ApplicationEvent { private String name; private String msg; public TestEvent(Object source){
super(source);
} public TestEvent(Object source, String name, String msg) {
super(source);
this.name = name;
this.msg = msg;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
}
}
  • 其次定义事件监听
/**
* @Title:
* @Auther: hangyu
* @Date: 2019/3/13
* @Description
* @Version:1.0
*/
@Component
public class TestEventListener implements ApplicationListener<TestEvent> { @Async
@Override
public void onApplicationEvent(TestEvent testEvent) {
System.out.println("姓名:"+testEvent.getName()+"得到消息:"+testEvent.getMsg());
}
}
  • 使用容器发布事件

/**
* @Title:
* @Auther: hangyu
* @Date: 2019/3/13
* @Description
* @Version:1.0
*/
@Component
public class TestEventPublisher { @Autowired
private ApplicationContext applicationContext; public void pushlish(String name, String msg){
applicationContext.publishEvent(new TestEvent(this, name,msg));
}
}
  • 测试事件是否能够生效
/**
* @Title:
* @Auther: hangyu
* @Date: 2019/3/13
* @Description
* @Version:1.0
*/
@Configuration
@ComponentScan("cn.*.event")
public class EventConfig {
} /**
* @Title:
* @Auther: hangyu
* @Date: 2019/3/13
* @Description
* @Version:1.0
*/
public class TestMain { private static AnnotationConfigApplicationContext context; public static void main(String[] args) {
start();
} private static void start() {
if (context == null) {
context=new AnnotationConfigApplicationContext(EventConfig.class);
}
context.getBean(TestEventPublisher.class).pushlish("hangyu","申请退款!");
}
}
 
输出打印结果

最后有一个思考:ApplicationEvent事件执行部分和起一个TaskExecutor去执行 有啥区别吗?反正都是异步。

可以这样实现;

 @Autowired
private AsyncExecutor asyncExecutor; Executor executor = asyncExecutor.getAsyncExecutor();
executor.execute(
//具体业务
}); @Configuration
@EnableAsync
public class AsyncExecutor implements AsyncConfigurer { // 日志
static final Logger logger = LoggerFactory.getLogger(AsyncExecutor.class); public Executor getAsyncExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.setQueueCapacity(20000); taskExecutor.setKeepAliveSeconds(120); taskExecutor.setAllowCoreThreadTimeOut(true); taskExecutor.initialize(); return taskExecutor;
}
}

还可以这样实现;

    <!-- 异步线程池 -->
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数 -->
<property name="corePoolSize" value="3" />
<!-- 最大线程数 -->
<property name="maxPoolSize" value="10" />
<!-- 队列最大长度 >=mainExecutor.maxSize -->
<property name="queueCapacity" value="25" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="300" />
<!-- 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃. -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean> @Resource
private TaskExecutor taskExecutor; taskExecutor.execute(new Runnable() {
@Override
public void run() {
//具体业务
}
}
 
这就是注解方式和直接引用方式,本质是一样的

我的思考:ApplicationEvent是观察者设计模式,这种设计模式使得主题和观察者之间的耦合度降低,松耦合是面向对象设计中很重要的一个原则,最终也是使用@Async来实现异步。而TaskExecutor则是启动一个线程池任务异步执行任务,两者效果一样,但原理不同。

通过我的思考,又带来一个疑问:那观察者模式是不是就是我们MQ中的发布订阅模式呢?只不过观察者模式是进程内的,而MQ是跨进程的?就这唯一的区别吗?

经过一些资料的查阅:大多数地方观察者模式约等于发布订阅模式,但是观察者模式是由具体目标调度的,而发布/订阅模式是统一由调度中心调的,所以观察者模式的订阅者与发布者之间是存在依赖的,而发布/订阅模式则不会。

所以说观察者模式是小米加步枪,发布订阅模式是95式自动步枪,是它的进化版!

作者:杭宇_8ba6
链接:https://www.jianshu.com/p/e03c5c53d2e9
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

如何实现Application event,观察者模式的更多相关文章

  1. Spring 事件:Application Event

    Spring Application Event Spring 的事件(Application Event)为 Bean 与 Bean 之间的消息通信提供了支持.当一个 Bean 处理完一个任务之后, ...

  2. Spring Application Event Example

    Spring Application Event 项目结构 工程下载 https://github.com/xiaoheike/SpringApplicationEventExample.git Sp ...

  3. Spring Boot实战笔记(四)-- Spring常用配置(事件Application Event)

    一.事件(Application Event) Spring的事件为Bean和Bean之间的消息通信提供了支持.当一个Bean处理完一个任务之后,希望另一个Bean知道并能做相应的处理,这时我们就需要 ...

  4. SpringBoot -- 事件(Application Event)

    Spring的事件为Bean与Bean之间的消息通信提供了支持,当一个Bean处理完一个任务之后,希望另外一个Bean知道并能做相应的处理,这时我们就需要让一个Bean监听当前Bean所发送的事件. ...

  5. spring boot: 一般注入说明(五) @Component, application event事件为Bean与Bean之间通信提供了支持

    spring的事件,为Bean与Bean之间通信提供了支持,当一个Bean处理完成之后,希望另一个Bean知道后做相应的事情,这时我们就让另外一个Bean监听当前Bean所发送的事件. spring的 ...

  6. 从命令模式的维度理解Spring 之Application Event

    Spring的事件(Application Event)为Bean与Bean之间的信息通讯提供了支持.当一个Bean处理完一个任务之后,希望另一Bean指定并能做相应的处理,这时我们就需要让另外一个B ...

  7. spring 事件(Application Event)

    spring 事件为bean 与 bean之间传递消息.一个bean处理完了希望其余一个接着处理.这时我们就需要其余的一个bean监听当前bean所发送的事件. spring事件使用步骤如下: 1.先 ...

  8. c++ 设计模式5 (Observer / Event 观察者模式)

    3.3 观察者模式 (Observer)/发布-订阅模式 动机: 在软件构建过程中,我们需要为某些对象建立一种“通知依赖关系”——一个对象(目标对象)的状态发生改变,所有的依赖对象(观察者对象)都能得 ...

  9. 事件(Application Event)

    Spring的事件(Appllcation Event)为Bean与Bean之间的消息通信提供了支持.当一个Bean处理完一个任务后,希望另一个Bean知道并能做相应的处理,这种情况可以让另一个Bea ...

随机推荐

  1. Springboot中redisTemplate乱码或json转换问题

    问题1 用RedisTemplate存入map值的时候,用rdm可视化打开,看到的是转码之后的数据,如图: 存入的方法为: public boolean hmset(String key, Map&l ...

  2. Day1-7【Scrum 冲刺博客集合】

    Day1-Day7博客链接 Day1[Scrum 冲刺博客] Day2[Scrum 冲刺博客] Day3[Scrum 冲刺博客] Day4[Scrum 冲刺博客] Day5[Scrum 冲刺博客] D ...

  3. cglib、orika、spring等bean copy工具性能测试和原理分析

    简介 在实际项目中,考虑到不同的数据使用者,我们经常要处理 VO.DTO.Entity.DO 等对象的转换,如果手动编写 setter/getter 方法一个个赋值,将非常繁琐且难维护.通常情况下,这 ...

  4. 利用promise实现间隔1s打印1,2,3

    利用promise结合数组的rduce方法 let arr = [1, 2, 3]; arr.reduce((pre, cur) => { return pre.then(() => { ...

  5. 原生js获取页面所有的checkbox

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. ASP自动刷新页面的实现方法总结

    1) <meta http-equiv="refresh" content="10"> 10表示间隔10秒刷新一次 2) <script> ...

  7. 【题解】「SP867」 CUBES - Perfect Cubes

    这道题明显是一道暴力. 暴力枚举每一个 \(a, b, c, d\) 所以我就写了一个暴力.每个 \(a, b, c, d\) 都从 \(1\) 枚举到 \(100\) #include<ios ...

  8. AcWing 339 .圆形数字

    大型补档计划 题目链接 设 \(f[i][j]\) 表示二进制下,数字有 \(i\) 位, \(0\) 的个数 - \(1\) 的个数 \(=\) \(j\) 的方案数 \(f[0][0] = 1;\ ...

  9. OpenCV Error: Assertion failed (src.size == dst.size && src.channels() == dst.channels()) in cvConvertScale

    发现问题:在做kinect采集的深度图去噪的时候遇到了cvConvertScale格式转换的问题. OpenCV Error: Assertion failed (src.size == dst.si ...

  10. SpringBoot快速入门(理论篇)

    说在最前 此篇文章,为Spring Boot理论骗,所谓的理论篇就是几乎不会出现代码,只介绍一些理论知识,这些理论知识对你你以后快速上手Spring Boot有非常大的用处! 什么是Spring Bo ...