package com.tujia.rba.distribution.service.platform.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author 无名小生 Date: 2018-08-28 Time: 22:07
* @version $Id$
*/
@Deprecated
public abstract class BasePushService<T> extends Thread {
private static Logger logger = LoggerFactory.getLogger(BasePushService.class);
private volatile static boolean isRunning = false;
private volatile static boolean isStopConsume = false;
private volatile static boolean isStopProduce = false;
private static List<Object> queue = new ArrayList<>();
private static int length = 10000;
/**
* 往队列添加数据
*
* @param data
* @throws InterruptedException
*/
protected void pushByDelayQueue(T data) throws InterruptedException {
if (!isRunning) {
logger.info("开始执行消费行为,当前消费者线程id : " + Thread.currentThread().getId());
this.start();
}
synchronized (queue) {
logger.info("开始——添加——推送消息,当前生产者线程id :" + Thread.currentThread().getId());
if (queue.size() >= length) {
logger.error("队列数据堆积,开始等待消费后继续添加数据,数据类型为:{}", queue.get(0).getClass().getSimpleName());
isStopProduce = true;
queue.wait();
}
isStopProduce = false;
queue.add(data);
if (isStopConsume) {
queue.notifyAll();
}
}
}
/**
* 异步消费数据
*/
@Override
public void run() {
logger.info("开始——消费——推送消息,当前消费者线程id : " + Thread.currentThread().getId());
while (true) {
try {
T obj;
synchronized (queue) {
isRunning = true;
if (queue.size() == 0) {
isStopConsume = true;
if (isStopProduce) {
queue.notifyAll();
}
queue.wait();
}
isStopConsume = false;
obj = (T) queue.remove(0);
}
doSomething(obj);
} catch (InterruptedException | IOException e) {
logger.error("消费推送消息失败当前消费者线程id :" + Thread.currentThread().getId(), e);
}
}
}
/**
* 业务逻辑
*
* @param obj
* @return
* @throws IOException
*/
protected APIResponse doSomething(T obj) throws IOException {
System.out.println("当前消费线程id" + Thread.currentThread().getId());
Object result = new Object();
return callBack(result);
}
/**
* 回调接口
*
* @param resultVo
* @return
*/
protected abstract APIResponse callBack(Object resultVo);
}