本文主要研究一下cheddar的events

Event

Cheddar/cheddar/cheddar-events/src/main/java/com/clicktravel/cheddar/event/Event.java

public interface Event {

    String type();

    String serialize();

}
Event接口定义了type、serialize方法

AbstractEvent

Cheddar/cheddar/cheddar-events/src/main/java/com/clicktravel/cheddar/event/AbstractEvent.java

public abstract class AbstractEvent implements Event {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.registerModule(new JodaModule());
    }

    @Override
    public abstract String type();

    public static <T extends Event> T newEvent(final Class<T> eventClass, final String serializedEvent) {
        try {
            return MAPPER.readValue(serializedEvent, eventClass);
        } catch (final IOException e) {
            throw new IllegalStateException("Could not instantiate event " + eventClass.getName());
        }
    }

    @Override
    public final String serialize() {
        try {
            return MAPPER.writeValueAsString(this);
        } catch (final Exception e) {
            throw new IllegalStateException("Could not serialize event: [" + this + "]", e);
        }
    }

}
AbstractEvent声明实现Event接口,它实现了serialize方法,采用jackson序列化为json;然后声明type抽象方法供子类实现

EventHandler

Cheddar/cheddar/cheddar-events/src/main/java/com/clicktravel/cheddar/event/EventHandler.java

public interface EventHandler<E extends Event> {

    void handle(final E event);

    Class<? extends E> getEventClass();

}
EventHandler接口定义了handle、getEventClass方法

EventPublisher

Cheddar/cheddar/cheddar-events/src/main/java/com/clicktravel/cheddar/event/EventPublisher.java

public abstract class EventPublisher<E extends Event> {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final MessagePublisher<TypedMessage> messagePublisher;

    protected EventPublisher(final MessagePublisher<TypedMessage> messagePublisher) {
        this.messagePublisher = messagePublisher;
    }

    public void publishEvent(final E event) {
        logger.debug("Publishing: " + event);
        final TypedMessage typedMessage = new SimpleMessage(event.type(), event.serialize());
        messagePublisher.publish(typedMessage);
    }

}
EventPublisher方法定义了publishEvent方法,它创建SimpleMessage,然后执行messagePublisher的publish来发布消息

小结

cheddar定义了Event接口及AbstractEvent抽象类,其子类需要实现type方法;EventHandler接口定义了handle、getEventClass方法;EventPublisher方法定义了publishEvent方法,它创建SimpleMessage,然后执行messagePublisher的publish来发布消息。

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...