SpringBoot使用EventBus实现事件监听并消费_springboot evenbus_他头发很多的博客-CSDN博客

一,依赖

<dependency>  <groupId>com.google.guava</groupId>  <artifactId>guava</artifactId>  <version>22.0</version></dependency>

二,配置文件

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; @Configurationpublic 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 */@Componentpublic 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> T getBean(String name) throws BeansException    {        return (T) beanFactory.getBean(name);    }     /**     * 获取类型为requiredType的对象     *     * @param clz     * @return     * @throws     *     */    public static <T> T getBean(Class<T> clz) throws BeansException    {        T result = (T) beanFactory.getBean(clz);        return result;    } }

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

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


原网址: 访问
创建于: 2023-03-16 10:42:05
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论