sequence
This paper mainly studies cheddar’s events
Event
Cheddar/cheddar/cheddar-events/src/main/java/com/clicktravel/cheddar/event/Event.java
public interface Event {
String type();
String serialize();
}
Copy the code
The Event interface defines the type, serialize methods
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); }}}Copy the code
The AbstractEvent declaration implements the Event interface, which implements the serialize method using Jackson to serialize to JSON. The type abstract method is then declared for subclasses to implement
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();
}
Copy the code
EventHandler defines the Handle and getEventClass methods
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); }}Copy the code
The EventPublisher method defines the publishEvent method, which creates SimpleMessage and then executes messagePublisher’s publish to publish the message
summary
Cheddar defines the Event interface and AbstractEvent class, whose subclass needs to implement the Type method. EventHandler defines the Handle and getEventClass methods. The EventPublisher method defines the publishEvent method, which creates SimpleMessage and then executes messagePublisher’s publish to publish the message.
doc
- Cheddar