Skip to content
java
import cn.hutool.core.util.RandomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 用户编号生成
 *
 * @author knight
 */
@Slf4j
@RequiredArgsConstructor
public class UserNoGenerate {

    private static final String USER_NO_BIT_KEY = "app:userNo:bitmap";

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 用户编号是否存在
     */
    public boolean exist(long userNo) {
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().getBit(USER_NO_BIT_KEY, userNo));
    }

    public Integer next() {
        int userNo;
        boolean exists;
        int attempts = 0;

        do {
            userNo = generateUserNo();
            exists = exist(userNo);
            attempts++;
        } while (exists);

        if (attempts > 3) {
            log.warn("用户编号生成次数: {}", attempts);
        }

        // 设置该编号为已使用
        stringRedisTemplate.opsForValue().setBit(USER_NO_BIT_KEY, userNo, true);
        return userNo;
    }

    private Integer generateUserNo() {
        String userNoStr = RandomUtil.randomNumbers(9);
        if (userNoStr.startsWith("0")) {
            userNoStr = "1" + userNoStr.substring(1);
        }
        return Integer.parseInt(userNoStr);
    }

}