zjh
2025-01-06 1ce606a5cd06b859a57eabf8b12c4fb3704168b4
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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;
import java.util.Random;
 
/**
 * @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";
 
//    private static final UidGenerator uidGenerator = new DefaultUidGenerator();  // 使用默认的Snowflake生成器
 
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
    public synchronized String generateLisID(String prefix) {
        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(prefix+"%s%05d", yyMMdd, lastId);
    }
 
 
    //生成体检号用
    private static long lastTimestamp = -1;
    private static final Random random = new Random();
 
    public static synchronized String getTjNumber() {
        long timestamp = System.currentTimeMillis();  // 获取当前时间戳(毫秒)
 
        // 如果时间戳和上次生成的时间戳相同,生成一个新的随机数
        if (timestamp == lastTimestamp) {
            return String.format("%09d", (timestamp % 1000000000) + random.nextInt(900) + 100);
        } else {
            lastTimestamp = timestamp;  // 更新最后生成时间戳
            return String.format("%09d", (timestamp % 1000000000) + random.nextInt(900) + 100);
        }
    }
 
 
//    使用分布式ID生成器(如Snowflake)
    public static String generateExamNumber() {
//        long id = uidGenerator.getUID();  // 获取生成的唯一ID
//        return String.format("%09d", Math.abs(id) % 1000000000);  // 格式化为9位
        return null;
    }
 
}