/**
 * 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.TOperLogS;
import com.crunii.micro.platform.service.OperLogService;
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年5月15日下午4:44:39
 */
@Slf4j
@Component
public class OperLogFastQueueHandler extends AbstractFastQueueHandler<TOperLogS> {

	@Autowired
	private OperLogService operLogService;

	private static ExecutorService executor = new ThreadPoolExecutor(4, 8, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(),
			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<TOperLogS> event, long sequence, boolean endOfBatch) {
		TOperLogS operLog = event.getVal();
		if (operLog == null) {
			log.info("TOperLog is null");
			return;
		}
		sendAsync(operLog);
		//释放资源,必须释放否则可能引起内存溢出
		event.clear();
	}

	private void sendAsync(TOperLogS operLog) {
		executor.execute(() -> {
			try {
				operLogService.createTOperLog(operLog);
			} catch (Exception e) {
				log.error("Direct insert database error!{}", operLog, e);
			}
		});
	}

}
