| | |
| | | package com.ruoyi.approve.utils; |
| | | |
| | | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; |
| | | import com.ruoyi.approve.mapper.ApproveProcessMapper; |
| | | import com.ruoyi.approve.pojo.ApproveProcess; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.data.redis.core.StringRedisTemplate; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.annotation.Resource; |
| | | import java.text.SimpleDateFormat; |
| | | import java.time.LocalDate; |
| | | import java.time.format.DateTimeFormatter; |
| | | import java.util.Calendar; |
| | | import java.util.Date; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | |
| | |
| | | this.redisTemplate = redisTemplate; |
| | | } |
| | | |
| | | /** |
| | | /**查缓存 |
| | | * 获取指定计数器在今日的数值,并自增1 |
| | | * @param counterName 计数器名称(例如:login_count、order_count) |
| | | * @return 今日自增后的计数值 |
| | |
| | | return count; |
| | | } |
| | | |
| | | @Autowired |
| | | private ApproveProcessMapper approveProcessMapper; |
| | | |
| | | /** |
| | | * 获取当前时间的 开始日期 ,结束日期 |
| | | * @return |
| | | */ |
| | | public static StartAndEndDateDto getDateTime(){ |
| | | SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); |
| | | Date date = new Date(); |
| | | Calendar cal = Calendar.getInstance(); |
| | | cal.setTime(date); |
| | | cal.add(Calendar.DATE,1); |
| | | String startDateTime = simpleDateFormat.format(date); |
| | | String endDateTime = simpleDateFormat.format(cal.getTime()); |
| | | StartAndEndDateDto startAndEndDateDto = new StartAndEndDateDto(); |
| | | startAndEndDateDto.setStartDate(startDateTime); |
| | | startAndEndDateDto.setEndDate(endDateTime); |
| | | return startAndEndDateDto; |
| | | } |
| | | |
| | | /**查数据库 |
| | | * 获取指定计数器在今日的数值,并自增1 |
| | | * @return 今日自增后的计数值 |
| | | */ |
| | | public long incrementAndGetByDb() { |
| | | String key = "approveNumHSXNY"; |
| | | |
| | | // 1. 先尝试从 Redis 自增(原子操作) |
| | | Long num = redisTemplate.opsForValue().increment(key); |
| | | |
| | | // 2. 如果是第一次(说明 key 不存在) |
| | | if (num == null || num == 1L) { |
| | | |
| | | // 查询数据库当前最大值(更合理) |
| | | StartAndEndDateDto dateTime = getDateTime(); |
| | | |
| | | LambdaQueryWrapper<ApproveProcess> wrapper = new LambdaQueryWrapper<>(); |
| | | wrapper.eq(ApproveProcess::getApproveDelete, 0) |
| | | .ge(ApproveProcess::getCreateTime, dateTime.getStartDate()) |
| | | .lt(ApproveProcess::getCreateTime, dateTime.getEndDate()); |
| | | |
| | | Long count = approveProcessMapper.selectCount(wrapper); |
| | | |
| | | long start = (count == null ? 0 : count) + 1; |
| | | |
| | | // 设置初始值(避免覆盖并发) |
| | | redisTemplate.opsForValue().set(key, String.valueOf(start), 1L, TimeUnit.HOURS); |
| | | |
| | | return start; |
| | | } |
| | | |
| | | return num; |
| | | } |
| | | |
| | | /** |
| | | * 获取指定计数器在今日的当前数值 |
| | | * @param counterName 计数器名称 |