zhaowenxuan
2024-10-11 2a9edc5ec5c33af656e8e8af768a25760f0dfc92
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.ltkj.common.utils;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * @Company: 西安路泰科技有限公司
 * @Author: zhaowenxuan
 * @Date: 2024/10/10 14:55
 */
@Component
public class IdUtils {
 
    private static final String LIS_LAST_ID_KEY = "id:generate:lis:id";
    private static final String LIS_CURRENT_DATE_KEY = "id:generate:lis:currentDate";
 
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
    public synchronized String generateLisID() {
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String storedDate = stringRedisTemplate.opsForValue().get(LIS_CURRENT_DATE_KEY);
        String lastIdStr = stringRedisTemplate.opsForValue().get(LIS_LAST_ID_KEY);
        int lastId;
        if (storedDate == null || !storedDate.equals(currentDate)) {
            lastId = 1;
            stringRedisTemplate.opsForValue().set(LIS_LAST_ID_KEY, String.valueOf(lastId));
            stringRedisTemplate.opsForValue().set(LIS_CURRENT_DATE_KEY, currentDate);
        } else {
            lastId = Integer.parseInt(lastIdStr) + 1;
            stringRedisTemplate.opsForValue().set(LIS_LAST_ID_KEY, String.valueOf(lastId));
        }
        String yyMMdd = currentDate.substring(2);
        return String.format("%s%06d", yyMMdd, lastId);
    }
 
}