首先直接看如何使用ThreadLocal
public class TaobaoPurchaseTaskNettyHandler {
private static final String END_WORKING_TIME = "230000";
private static Logger logger = LoggerFactory.getLogger(TaobaoPurchaseTaskNettyHandler.class);
private static ThreadLocal<TaobaoPurchaseOperatorNetty> operatorThreadLocal = new ThreadLocal<>();
public static CheckPricePlaceOrderAndPayResponse placeOrderAndPay(CheckPricePlaceOrderAndPayRequest placeOrderAndPayRequest)throws Exception{
// if(!checkPriceOrder.getOldOrderId().equals("75579381339"))
// return;
// if(!task.getTaobaoOrderId().equals("75167292951"))
// return;
MDC.put(CrawlerConstants.MDC_TRACEID_PLACEHOLDER, RandomStringUtils.randomAlphanumeric(10));
//TaobaoPurchaseOperation.isOrderNeedTaobaoPurchase(task)&&
if ( DateTimeUtil.time6().compareTo(END_WORKING_TIME) <= 0){
logger.info(new Gson().toJson(placeOrderAndPayRequest));
TaobaoPurchaseOperatorNetty operator = getOperator();
return operator.OperateTaobaoPurchase(placeOrderAndPayRequest);
}else{
return null;
}
}
private static TaobaoPurchaseOperatorNetty getOperator(){
TaobaoPurchaseOperatorNetty operator = operatorThreadLocal.get();
if(operator == null){
operator = new TaobaoPurchaseOperatorNetty();
operatorThreadLocal.set(operator);
}
return operator;
}
}
主要三个步骤,1,你要处理那个类
2,是否在一个ThreadLocal里,没有的话,就新建一个,如果有的话,就从ThreadLocal里取出来
3,最后在ThreadLocal的处理类上进行操作。
感觉思想真的很简单,但是有一个问题,如果处理的过程很多,同一个处理线程里,多个线程(不可能的啦),是不是会奔溃掉。