
com.github.df.restypass.event.EventBus Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of resty-pass Show documentation
Show all versions of resty-pass Show documentation
High-Performance Restful Client Library
package com.github.df.restypass.event;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
/**
* 事件总线
* Created by darrenfu on 17-7-23.
*/
@SuppressWarnings("WeakerAccess")
@Slf4j
public class EventBus {
/**
* 事件-消费者缓存(eventKey->Consumer)
*/
private static ConcurrentHashMap> eventMap = new ConcurrentHashMap<>();
/**
* 注册事件和消费者
*
* @param event the event
* @param consumer the consumer
*/
static void registerEventAndConsumer(String event, Consumer consumer) {
// 不存在 event
if (!eventMap.containsKey(event)) {
//
List consumerList = new CopyOnWriteArrayList<>();
consumerList.add(consumer);
// 新增
List existConsumers = eventMap.putIfAbsent(event, consumerList);
if (existConsumers != null) {
// 并发,新增
existConsumers.add(consumer);
}
} else {
// event已存在
List consumerList = eventMap.get(event);
if (consumerList != null) {
consumerList.add(consumer);
}
}
if (log.isTraceEnabled()) {
log.trace("注册事件:{}成功", event);
}
}
/**
* 消费事件
*
* @param the type parameter
* @param event the event
* @param obj the obj
*/
@SuppressWarnings("unchecked")
static void emitEvent(String event, T obj) {
List consumers = eventMap.get(event);
if (consumers != null && eventMap.size() > 0) {
for (Consumer consumer : consumers) {
consumer.accept(obj);
}
}
if (log.isTraceEnabled()) {
log.trace("消费事件:{},参数:{}", event, obj);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy