与番石榴事件总线的Guice

时间:2016-08-31 14:59:46

标签: java guava guice event-bus

我正在使用Gauva事件总线在rest api中发布事件。使用Guice注入事件总线。

@Singleton
public class EventBusProvider implements Provider<EventBus> {
    private final EventSubscriberImpl eventSubscriber;
    private EventBus eventBus;

    @Inject
    public EventBusProvider(EventSubscriberImpl eventSubscriber) {
        this.eventSubscriber = eventSubscriber;
        eventBus = new AsyncEventBus(Executors.newCachedThreadPool());
        eventBus.register(this.eventSubscriber);
    }

    @Override
    public EventBus get() {
        return eventBus;
    }
} 

活动订阅者。

@Singleton
public class EventSubscriberImpl implements EventSubscriber {
    private static final org.slf4j.Logger LOGGER =
            LoggerFactory.getLogger(EventSubscriberImpl.class);

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handleEvent(BaseEvent event) {
        try {
            LOGGER.info(event.getClass() + " event fired");
            event.handleEvent();
        } catch (Exception e) {
            LOGGER.info("Eventbus subscriber " + e.getMessage());
        }
    }
}

向订阅者发布事件的事件调度程序。

public class EventDispatcher {
    private static final org.slf4j.Logger LOGGER =
            LoggerFactory.getLogger(EventDispatcher.class);
    private EventBus eventBus;

    @Inject
    public EventDispatcher(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    public void postEvent(BaseEvent event) {
        eventBus.post(event);
    }

    public void postAsyncEvent(BaseEvent event) {
        LOGGER.info("publishing event ", event.getClass());
        eventBus.post(event);
    }

    public void register(EventSubscriber eventSubscriber) {
        eventBus.register(eventSubscriber);
    }
} 

我将事件注入我的服务类,然后在事件总线上发布。

@Inject
public TokenServiceImpl(TokenEvent tokenEvent,
                        EventDispatcher eventDispatcher) {
    this.tokenEvent = tokenEvent;
    this.eventDispatcher = eventDispatcher;
}

public void doSomeStuffAndFireEvent() {
     //create a token
    tokenCreateEvent.setTokenId(token.getTokenId());
    tokenCreateEvent.setQueueId(token.getTokenQueueId());
    eventDispatcher.postAsyncEvent(tokenCreateEvent);
}

当我们对API执行一些负载测试时,我们注意到当事件被触发时,重复或复制了诸如tokenId和tokenQueueId之类的事件属性。所以,如果

Tokens 1, 2, 3 ,4 ,5 ,6, ..... 30 

是在循环中创建的,当事件被触发2,3,4,5,6事件丢失时,我们会看到为tokenId 20触发的多个事件。不确定其他事件丢失的原因。这是Guice注射的问题吗?

0 个答案:

没有答案