最近在做批量,怎么能看批量的进度了,所以写了一个计算的方法。
1、这个中主要用到了AtomicInteger
我们知道java并发机制中主要有三个特性需要我们去考虑,原子性、可见性和有序性。synchronized关键字可以保证可见性和有序性却无法保证原子性。而这个AtomicInteger的作用就是为了保证原子性。
import java.util.concurrent.atomic.AtomicInteger;
public interface ICount {
AtomicInteger shopGoodsCount = new AtomicInteger(0);
AtomicInteger shopGoodsSum = new AtomicInteger(0);
AtomicInteger shopNotCheckGoodsCount = new AtomicInteger(0);
AtomicInteger shopGoodsErrorCount = new AtomicInteger(0);
AtomicInteger proBrandsCount = new AtomicInteger(0);
AtomicInteger proBrandsSum = new AtomicInteger(0);
AtomicInteger proBrandsNotCheckCount = new AtomicInteger(0);
AtomicInteger proBrandsErrorCount = new AtomicInteger(0);
AtomicInteger proCategorysCount = new AtomicInteger(0);
AtomicInteger proCategorysSum = new AtomicInteger(0);
AtomicInteger proCategorysErrorCount = new AtomicInteger(0);
AtomicInteger elseCount = new AtomicInteger(0);
AtomicInteger elseErrorCount = new AtomicInteger(0);
ExceptionInner exception = new ExceptionInner();
class ExceptionInner{
Throwable exception;
String message;
public Throwable getException() {
return exception;
}
public void setException(Throwable exception) {
this.exception = exception;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2、在批量执行的时候设置不同的值
ICount.shopGoodsCount.set(0);
ICount.shopGoodsSum.set(0);
ICount.shopGoodsErrorCount.set(0);
ICount.shopNotCheckGoodsCount.set(0);
List<Goods> allGoods = GoodsService.findAllGoods();
ICount.shopGoodsSum.set(allProGoods.size());
循环或者error中设置如下:
ICount.shopNotCheckGoodsCount.getAndIncrement();
ICount.shopGoodsErrorCount.getAndIncrement();
然后进程的接口可以这么写
@RequestMapping(value = "/api/viewProgress", method = RequestMethod.GET)
@ResponseBody
public Map<String,Integer> viewProgress() {
TreeMap<String, Integer> result = new TreeMap<>();
//商品的进度
result.put("goodsTotal",ICount.shopGoodsSum.get());
result.put("goodsError",ICount.shopGoodsErrorCount.get());
result.put("goodsNotCheckCount",ICount.shopNotCheckGoodsCount.get());
result.put("goodsAlreadSend",ICount.shopGoodsCount.get());
}