经常遇到这样的并发问题,相同的订单不允许并发,不同的订单允许并发。(特别是在创建订单,支付的时候,如果相同的订单并发了,很容易出问题)
解决方式如下:
首先定义一个map
/**
* 用于防止并发的全局变量
*/
private static HashMap<String,Integer> groupVariable=new HashMap<String,Integer>();
key=操作方式+订单id,比如支付订单就是PayOrder+id作为key,创建订单就是CreateOrder+id作为key。
然后每次创建订单或者支付的时候就从map里面取key信息(取key的方法要加上同步锁),如果没有取到,说明当前没有人在创建订单或者支付订单,那么没有并发。
否则,说明已经有人在操作了,抛出异常。
@Override
public Integer putGroupVariableValue(String type, String value) throws Exception {
synchronized (groupVariable) {
if (groupVariable.containsKey(type + value)) {
if(BBOOConstants.GroupVariable_type_B2BPay.equals(type)){
throw new Exception("有其他人正在支付该订单,请刷新后重试!");
}else if(BBOOConstants.GroupVariable_type_EtdzCreateOrder.equals(type)){
throw new Exception("有其他人正在处理该订单,请刷新后重试!");
}else if(BBOOConstants.GroupVariable_type_Import.equals(type)){
throw new Exception("有其他人也在导入该订单,请刷新后重试!");
}else if(BBOOConstants.GroupVariable_type_B2BCreateOrder.equals(type)){
throw new Exception("该订单其他人正在创单,请刷新后重试!");
}
} else {
groupVariable.put(type + value, 1);
}
}
return groupVariable.get(type+value);
}