如何使用spring配置Async和Sync Event发布者
我试图使用spring事件实现一个事件框架。我开始知道spring事件框架的默认行为是sync。 但是在Spring上下文初始化期间,如果它找到一个id为applicationEventMulticaster的bean,它就会表现为Async。
现在我想在我的应用程序中同时拥有同步和异步事件发布者,因为某些事件需要同步发布。 我尝试使用SysncTaskExecutor配置同步事件多播器,但我找不到将其注入我的AsyncEventPublisher的applicationEventPublisher属性的方法。 我的spring配置文件如下
有人可以帮我从这里出去吗 ?
不,你不能这样做,spring initApplicationEventMulticaster只是init一个,而BeanName必须是applicationEventMulticaster。 所以你可以选择下面的Executor之一:
– org.springframework.core.task.SyncTaskExecutor
– org.springframework.core.task.SimpleAsyncTaskExecutor
– 你自己的执行者:org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
无论如何,您可以修改org.springframework.context.event.SimpleApplicationEventMulticaster来添加您的逻辑,然后您可以控制是否需要同步/异步
/** * Initialize the ApplicationEventMulticaster. * Uses SimpleApplicationEventMulticaster if none defined in the context. * @see org.springframework.context.event.SimpleApplicationEventMulticaster */ protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isDebugEnabled()) { logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isDebugEnabled()) { logger.debug("Unable to locate ApplicationEventMulticaster with name '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "': using default [" + this.applicationEventMulticaster + "]"); } } }
我不适合使用stackoverflow进行编辑。 请原谅我。
- 和SyncTaskExecutor
我不需要添加您可以很清楚的评论。 这是同步的。 此Executor按顺序运行任务,并阻止每个任务。
public class SyncTaskExecutor implements TaskExecutor, Serializable { /** * Executes the given {@code task} synchronously, through direct * invocation of it's {@link Runnable#run() run()} method. * @throws IllegalArgumentException if the given {@code task} is {@code null} */ @Override public void execute(Runnable task) { Assert.notNull(task, "Runnable must not be null"); task.run(); }
}
- SimpleAsyncTaskExecutor
这个类非常大,所以我只选择代码段。 如果你给threadFactory,将从这个工厂检索Thread,或者将创建新的Thread。
protected void doExecute(Runnable task) { Thread thread = (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task)); thread.start(); }
- ThreadPoolTaskExecutor类
这个类使用jdk5的当前pkg ThreadPoolTaskExecutor。 但是spring封装了function。 spring擅长这种方式,jdk6的当前和jdk7的当前pkg有一些差别。 这将从ThreadPool获取Thread并重用它,执行每个任务Asynchronized。 如果您想了解更多详细信息,请参阅JKD源代码。