一,依赖
com.google.guava guava22.0
二,配置文件
import com.atzhi.bang.thread.HandlerThread;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
@Configuration
public class EventBusConfig {
@Bean
public EventBus registerEventBus() {
AsyncEventBus asyncEventBus = new AsyncEventBus("eventBusName", Executors.newFixedThreadPool(100));
asyncEventBus.register(handlerThread());
return asyncEventBus;
}
@Bean
public HandlerThread handlerThread() { //HandlerThread 这个类需要有一个消费的方法,如下
return new HandlerThread();
}
}
三,调用这个EventBus事件监听配置不能直接注入到对应的方法中,需要使用SpringUtil.getBean()来注入
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
@SuppressWarnings("unchecked")
public static T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
}
public static T getBean(Class clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
}
四,注入EventBus后调用他的post()方法传入事件信息给对应的方法处理,也就是上面说到的消费方法
@Subscribe @AllowConcurrentEvents这两个注解一定要加上,不然post传的参接收不到



