//controller里面使用锁
ActivityRedPacket ap = customerService.getActivityRedPacket(params);
if (synchronizedUtil.lockActivyId.containsKey(ap.getId())) {//MAP(key)锁里面是否存在锁
logger.info("<----------------领取红包客户:" + customeid + "多次操作领取红包!---------------------->");
return;
} else {
synchronizedUtil.synchronizedActivyId(ap.getId());/添加锁
}
synchronized (synchronizedUtil.lockActivyId.get(ap.getId())) {//获取锁
try{
//逻辑
}finally{
synchronizedUtil.lockActivyId.remove(ap.getId());//释放锁(移除MAP KEY 值)
}
}
//synchronizedUtil工具类
public class synchronizedUtil {
public static final ConcurrentHashMap<Integer, Object> lockVehicle = new ConcurrentHashMap<Integer, Object>();
public static final ConcurrentHashMap<Integer, Object> lockOrder = new ConcurrentHashMap<Integer, Object>();
public static final ConcurrentHashMap<Integer, Object> lockCustomerId = new ConcurrentHashMap<Integer, Object>();
public static final ConcurrentHashMap<Integer, Object> lockActivyId = new ConcurrentHashMap<Integer, Object>();
public static synchronized void synchronizedVehicle(Integer vehicleId){
if (!lockVehicle.containsKey(vehicleId)) {
lockVehicle.put(vehicleId, new Object());
return;
}
}
public static synchronized void synchronizedOrder(Integer OrderId){
if (!lockOrder.containsKey(OrderId)) {
lockOrder.put(OrderId, new Object());
return;
}
}
public static synchronized void synchronizedCustomerId(Integer CustomerId){
if (!lockCustomerId.containsKey(CustomerId)) {
lockCustomerId.put(CustomerId, new Object());
return;
}
}
public static synchronized void synchronizedActivyId(Integer ActivyId){
if (!lockActivyId.containsKey(ActivyId)) {//是否包含此ID锁不包含则放到MAP里
lockActivyId.put(ActivyId, new Object());
return;
}
}
}