流水号按天重置

1.代码结构

 private static ReadWriteLock lock = new ReentrantReadWriteLock();
 
@Override
public String getSerialNo(String workNo) throws ServiceException {
	// 加锁
	logger.debug("--------加锁---------------");
	lock.writeLock().lock();
	if (StringUtils.isBlank(workNo)) {
		throw new ServiceException("流水编码为空");
	}
	SerialInfo serialInfo = new SerialInfo();
	serialInfo.setWorkNo(workNo);
	SerialInfo info = serialInfoMapper.selectByPrimaryKey(serialInfo);
	if (info == null) {
		throw new ServiceException("查不到数据,请先设置流水编号");
	}
	try {
		String resetMode = info.getResetMode();
		String resetDate = DateUtil.getDateStr(info.getResetTime());
		String nowDate = DateUtil.getDateStr(new Date());
		if ("1".equals(resetMode)) {
			// 按照天重置
			if (!resetDate.substring(0, 10).equals(nowDate.substring(0, 10))) {
				info.setCurrentSerialNo(1);
				serialInfo.setResetTime(DateUtil.getCurrentDate());
			}
		} else if ("2".equals(resetMode)) {
			// 按照月重置
			if (!resetDate.substring(0, 7).equals(nowDate.substring(0, 7))) {
				info.setCurrentSerialNo(1);
				serialInfo.setResetTime(DateUtil.getCurrentDate());
			}
		} else if ("3".equals(resetMode)) {
			// 按照年重置
			if (!resetDate.substring(0, 4).equals(nowDate.substring(0, 4))) {
				info.setCurrentSerialNo(1);
				serialInfo.setResetTime(DateUtil.getCurrentDate());
			}
		}

		serialInfo.setCurrentSerialNo(info.getCurrentSerialNo() + 1);
		serialInfo.setModifyDate(DateUtil.getCurrentDate());
		serialInfoMapper.updateByPrimaryKeySelective(serialInfo);
		String serialNo = info.getCurrentSerialNo() + "";
		if (serialNo.length() < info.getSerialNoLength()) {
			// 左边补0
			int j = serialNo.length();
			for (int i = 0; i < info.getSerialNoLength() - j; i++) {
				serialNo = "0" + serialNo;
			}
		}
		if (StringUtils.isNotBlank(info.getPrefix())) {
			serialNo = info.getPrefix() + serialNo;
		}
		return serialNo;
	} catch (Exception e) {
		logger.error("流水号查询失败", e);
		throw new ServiceException("流水号查询失败");
	} finally {
		logger.debug("--------解锁---------------");
		lock.writeLock().unlock();
	}
}

**

2.数据库设计

流水号按天重置_第1张图片流水号按天重置_第2张图片

你可能感兴趣的:(技术分享)