1.在xml中定义bean
2.在使用的地方注册与监听事件
2.1定义基础事件
public interface BaseEvent extends Serializable {
Class sourceClz();
}
2.2 实现事件
@Getter
@Setter
public class AAEvent implements BaseEvent {
private static final long serialVersionUID = -4684935068654436812L;
private Level level;//事件级别,info、error等
private Codes errorEnum;
private String sequence;
private String operator;
private Collection errors;
private Class AAClz;
private Object[] args;
private String threadName;
private AAEvent () {
}
/**
*
*
* @param level
* @param errorEnum
* @param errors 异常信息
*/
public AAEvent (Level level, Codes errorEnum, Object[] args, Collection errors) {
this.level = level;
this.errorEnum = errorEnum;
this.errors = errors;
this.args = args;
this.threadName = Thread.currentThread().getName();
}
public Level getLevel() {
return level;
}
public Section section() {
if (errorEnum != null) {
return errorEnum.section();
}
return null;
}
@Override
public Class sourceClz() {
return this.AAClz;
}
2.3 定义事件适配器
public abstract class BaseEventBusListenerAdapter {
@Autowired
protected EventBus eventBus;
protected Logger logger = LoggerFactory.getLogger(getClass());
private static final String METHOD_NAME = "process";
@PostConstruct
protected void register() {
eventBus.register(this);
}
@Subscribe
@SuppressWarnings("all")
public void onEvent(AAEvent event) {
if (!support(event)) {
return;
}
// if (ReflectionUtils.findMethod(this.getClass(), METHOD_NAME, event.getClass()) != null) {
try {
if (!process((E)event)) {
logger.warn("handle event {} fail", event.getClass());
}
} catch (Exception e) {
logger.error(String.format("handle event %s exception", event.getClass()), e);
}
// }
}
public abstract boolean process(E e);
protected boolean support(BaseEvent event) {
if (event != null && event.sourceClz() != null) {
Class sourceClz = event.sourceClz();
if (this instanceof AbstractAnalyzer) {
return getClass().equals(sourceClz);
}
}
return false;
}
}
在继承类中,使用process(e)方法就可以接收到事件,并处理
2.4 发布事件
在类中:
// 解析异常
Collection errors = flatErrors(exception);
AAEvent extAnalysisEvent = new AAvent(level, anaCode, args, errors);
AAEvent.setAAClz(getClass());
setupAAEvent(AAEvent);
// 发内部消息
logger.info("发布EventBus事件:{}", extAnalysisEvent);
eventBus.post(extAnalysisEvent);
protected ExtAnalysisEvent setupAAEvent(AAEvent event) {
if (event != null && event.getSequence() == null) {
event.setSequence(ThreadLocalCache.get(ANALYSIS_SEQ_KEY));
}
return event;
}