/**
 * 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.platform.log.impl;

import com.crunii.micro.common.queue.ObjectEvent;
import com.crunii.micro.common.queue.impl.AbstractFastQueueHandler;
import com.crunii.micro.common.utils.StopUtil;
import com.crunii.micro.domain.entitysql.main.TBusiLogS;
import com.crunii.micro.platform.service.BusiLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * @author 田平 create 2019年12月27日上午10:23:01
 */
@Component
@Slf4j
public class BusiLogFastQueueHandler extends AbstractFastQueueHandler<TBusiLogS> {

	@Autowired
	private BusiLogService busiLogService;

	private ExecutorService executor = new ThreadPoolExecutor(4, 8, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(512),
			new RejectedExecutionHandler() {
				@Override
				public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
					if (!executor.isShutdown()) {
						try {
							executor.getQueue().put(r);
						} catch (InterruptedException e) {
							log.warn("executor Interrupted", e);
						}
					}
				}
			});

	@PreDestroy
	public void destroy() {
		StopUtil.stopES(executor);
	}

	@Override
	public void handler(ObjectEvent<TBusiLogS> event, long sequence, boolean endOfBatch) {
		TBusiLogS busiLog = event.getVal();
		if (busiLog == null) {
			log.info("BusiLog is null");
			return;
		}
		sendAsync(busiLog);
		//释放资源,必须释放否则可能引起内存溢出
		event.clear();
	}

	private void sendAsync(TBusiLogS busiLog) {
		executor.execute(() -> {
			try {
				busiLogService.createTBusiLog(busiLog);
			} catch (Exception e) {
				log.error("Direct insert database error!{}", busiLog, e);
			}
		});
	}

}
