Guava中EventBus使用

1.使用的好处:将发生事件的代码和处理事件的代码进行了解耦。比如发送消息。当某一件事情发生了之后,需要触发消息通知。可能需要短信,微信,邮件同时通知。在处理事件的代码中,可以配置三个Subscribe同时处理发消息类型的事件。另外,AsyncEventBus可以很方便的进行异步处理。

注册中心。EventBus中注册监听类。当有消息过来时,会根据消息的类型来消费。

@Component
public class EventBusCenter {

    private EventBus eventBus = new EventBus();

    private AsyncEventBus asyncEventBus = new AsyncEventBus(Executors.newCachedThreadPool());

    public void postSync(Object event) {
        eventBus.post(event);
    }

    public void postAsync(Object event) {
        asyncEventBus.post(event);
    }

    @PostConstruct
    public void init() {
        Map data = SpringContextUtil.getBeanByAnnotation(EventBusLisener.class);
        for (Map.Entry entry : data.entrySet()) {
            eventBus.register(entry.getValue());
            asyncEventBus.register(entry.getValue());
        }
        System.out.println("1");
    }
}

消息对象。

public class OrderCreateEvent {
    private long orderId;
    private long userId;
}

往EventBus中post消息。

@RequestMapping(value = "event")
@Controller
public class EventController {

    @Autowired
    EventBusCenter eventBusCenter;

    @RequestMapping(value = "create")
    public void test() {
        OrderCreateEvent event = new OrderCreateEvent(888L, 999L);
        eventBusCenter.postSync(event);
        System.out.println("zzz");
    }

    @RequestMapping(value = "message")
    public void test1() {
        MessageEvent event = new MessageEvent("elephant", "qqqqqqqqq");
        EventBus eventBus = new EventBus();
        // 需要注册实例。从spring环境中获取,否则无效
        //eventBus.register(MessageLisener.class);
        eventBus.register(SpringContextUtil.getBean(MessageLisener.class));
        eventBus.post(event);
        System.out.println("zzzz");
    }
}

工具类。

@Component
public class SpringContextUtil implements BeanFactoryPostProcessor {

    private static ConfigurableListableBeanFactory factory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        factory = beanFactory;
    }

    public static Map getBeanByAnnotation(Class annotationType) {
        Map data = factory.getBeansWithAnnotation(annotationType);
        return data;
    }

    public static Object getBean(Class c) {
        return factory.getBean(c);
    }
}

定义注解。将所有加了该注解的类标识为监听类。加入到注册中心。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface EventBusLisener {
}

你可能感兴趣的:(Guava中EventBus使用)