栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;


@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传的参接收不到

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1036526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号