聊聊cheddar的events

本文主要研究一下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 newEvent(final Class 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 {

    void handle(final E event);

    Class getEventClass();

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

EventPublisher

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

public abstract class EventPublisher {

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

    protected EventPublisher(final MessagePublisher 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

你可能感兴趣的:(java)