乐趣区

关于java:聊聊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 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

  • Cheddar
退出移动版