public interface BatchHandlerInterface<T> { /** * 分批回调方法 * */ public void handler(List<T> subList); }
--------------------------------------------------------
public abstract class BatchHandlerList<T> implements BatchHandlerInterface<T> { private static final Logger LOGGER = Logger.getLogger(BatchHandlerList.class); //每次处理条数 private Integer perNum; private List<T> aylist; public BatchHandlerList(Integer perNum, List<T> aylist) { super(); this.perNum = perNum; this.aylist = aylist; } /** * 分批调用方法 * */ public void handlerList(){ try{ if(aylist!=null && aylist.size() > 0){ int size = aylist.size(); int startIndex = 0; int endIndex = 1; int num = 1; if (size > perNum) { num = size / perNum; } for (int i = 1; i <= num; i++) { try { endIndex = (i) * perNum > size ? size : (i) * perNum; List<T> subList = aylist.subList(startIndex, endIndex); startIndex = perNum * i; if (subList!=null && subList.size() > 0) { handler(subList); } if (num == i && perNum * num < size) { //最后一批处理 subList = aylist.subList(perNum * num, size); if (subList.size() > 0) { handler(subList); } } } catch (Exception e) { LOGGER.error(" single batchHandlerList handler exception",e); } } } }catch(Throwable e){ LOGGER.error("batchHandlerList handler exception",e); //错误回调方法可以重写 errorHandler(); } } public void errorHandler(){}; }
--------------------------------------
调用
BatchHandlerList<User> handlerList = new BatchHandlerList<AcpInfo>(200,acpInfoList) { @Override public void handler(List<User> subList) { for(Usera:subList){ //逻辑处理 logger.info("",subList); } } }; handlerList.handlerList();