您的位置:首页 > 移动开发

BlogApp之spring整合Guava中的AsyEventBus异步事件

2016-02-13 10:01 513 查看
在这个博客的创作中,有许多地方需要使用到异步事件,在此选择了google的guava,这个里面有许多好用的工具库,

工程所需的maven依赖为:

<!--guava-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>


这里spring和AsyncEventBus的整合相对的整合要麻烦一些,EventBus的构造函数中有一个无参的构造函数,可以直接注入,但是

AsyncEventBus没有无参构造函数,最少也要有一个Executor的参数,因此在此主要编写这个参数的注入。

AsyncExecutor的编写为:

@Data
public class AsyncExecutor {

private Executor executor;

public AsyncExecutor() {
executor = Executors.newFixedThreadPool(10);
}
}


如此基本就完成了Executor的编写,现在需要一个工厂类ExecutorFactory。

ExecutorFactory:

public class ExecutorFactory {

public Executor getExecutorService(){
return Executors.newFixedThreadPool(8);
}
}


现在基本完成工厂类的编写,现在来编写配置文件:

<bean id="executorFactory" class="cn.com.factory.ExecutorFactory" />
<bean id="executor" factory-bean="executorFactory" factory-method="getExecutorService"></bean>
<bean id="eventBus" class="com.google.common.eventbus.AsyncEventBus">
<constructor-arg ref="executor" />
</bean>


如此,基本AsyncEventBus的配置就完成了,

但在handler的编写中,仍要将handler写进spring的配置文件中,以便方便注入。

在这里,如果有扫描的方法,还请其他人指教,毕竟在这里,有相当多的handler需要编写,每个handler都配置是比较麻烦的。

具体AsyncEventBus和spring的整合大致就到这里了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: