SpringBoot使用EventBus实现事件监听并消费

一,依赖


  com.google.guava
  guava
  22.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;

/**
 * spring工具类 方便在非spring管理环境中获取bean
 * 
 * @author wang qiang
 */
@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;
 
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
    {
        SpringUtils.beanFactory = beanFactory;
    }
 
    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws
     *
     */
    @SuppressWarnings("unchecked")
    public static  T getBean(String name) throws BeansException
    {
        return (T) beanFactory.getBean(name);
    }
 
    /**
     * 获取类型为requiredType的对象
     *
     * @param clz
     * @return
     * @throws
     *
     */
    public static  T getBean(Class clz) throws BeansException
    {
        T result = (T) beanFactory.getBean(clz);
        return result;
    }
 
}

四,注入EventBus后调用他的post()方法传入事件信息给对应的方法处理,也就是上面说到的消费方法

SpringBoot使用EventBus实现事件监听并消费_第1张图片

 @Subscribe @AllowConcurrentEvents这两个注解一定要加上,不然post传的参接收不到

你可能感兴趣的:(日常开发,spring,boot,java,spring)