Created
August 13, 2017 11:02
-
-
Save mymonkey110/aba58de452928bec2243848bb2c9b84a to your computer and use it in GitHub Desktop.
领域事件实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Serializable; | |
import java.util.Date; | |
/** | |
* 领域事件 | |
* Created by jiangwenkang on 16-11-17. | |
*/ | |
public interface DomainEvent extends Serializable { | |
Date occurredTime(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.collect.Lists; | |
import java.util.List; | |
import java.util.concurrent.ConcurrentHashMap; | |
/** | |
* 领域事件发布器 | |
* Created by jiangwenkang on 16-11-17. | |
*/ | |
public class DomainEventPublisher { | |
private static ConcurrentHashMap<Class<? extends DomainEvent>, List<DomainEventSubscriber<? extends DomainEvent>>> subscriberMap | |
= new ConcurrentHashMap<>(); | |
public synchronized static <T extends DomainEvent> void subscribe(Class<T> domainEventClazz, DomainEventSubscriber<T> subscriber) { | |
List<DomainEventSubscriber<? extends DomainEvent>> domainEventSubscribers = subscriberMap.get(domainEventClazz); | |
if (domainEventSubscribers == null) { | |
domainEventSubscribers = Lists.newArrayList(); | |
} | |
domainEventSubscribers.add(subscriber); | |
subscriberMap.put(domainEventClazz, domainEventSubscribers); | |
} | |
@SuppressWarnings("unchecked") | |
public static <T extends DomainEvent> void publish(final T domainEvent) { | |
if (domainEvent == null) { | |
throw new IllegalArgumentException("domain event is null"); | |
} | |
List<DomainEventSubscriber<? extends DomainEvent>> subscribers = subscriberMap.get(domainEvent.getClass()); | |
if (subscribers != null && !subscribers.isEmpty()) { | |
for (DomainEventSubscriber subscriber : subscribers) { | |
subscriber.handle(domainEvent); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 领域事件订阅器 | |
* Created by jiangwenkang on 16-11-17. | |
*/ | |
public interface DomainEventSubscriber<T extends DomainEvent> { | |
/** | |
* 订阅者处理事件 | |
* | |
* @param event 领域事件 | |
*/ | |
void handle(T event); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment