/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.queue.impl;

import com.crunii.micro.common.queue.ObjectEvent;
import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

/**
 * @author 田平 create 2019年3月4日下午3:48:42
 */
@Slf4j
public abstract class AbstractFastQueueHandler<T> implements EventHandler<ObjectEvent<T>> {

	/**
	 * @see com.lmax.disruptor.EventHandler#onEvent(java.lang.Object, long, boolean)
	 */
	@Override
	public void onEvent(ObjectEvent<T> event, long sequence, boolean endOfBatch) throws Exception {
		try {
			handler(event, sequence, endOfBatch);
		} catch (Exception e) {
			//新建线程抛出异常避免队列阻塞
			CompletableFuture.runAsync(() -> onException(event, sequence, endOfBatch, e));
		}
	}

	/**
	 * 提交执行
	 *
	 * @param event
	 * @param sequence
	 * @param endOfBatch
	 */
	public abstract void handler(ObjectEvent<T> event, long sequence, boolean endOfBatch);

	public void onException(ObjectEvent<T> event, long sequence, boolean endOfBatch, Exception e) {
		log.error("sequence:" + sequence + ",val:" + event.getVal().toString(), e);
	}

}
