redis ID生成器

public class IdSeqGenerator {
    /**
     * 昵称计数器,确保唯一性
     */
    private static final String ID_COUNTER_REDISKEY = "ID_COUNTER:";
    /**
     * ID前缀
     */
    private static final String NICKNAME_PREFIX           = "2017";
    /**
     * 日期起始点
     */
    private final static long   epoch                     = 1463108596098L;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 初始化redis计数器从 100000000 开始
     */
    @PostConstruct
    private void init() {
        try (Jedis jedis = jedisPool.getResource()) {
            if (jedis.get(ID_COUNTER_REDISKEY) == null) {
                jedis.set(ID_COUNTER_REDISKEY, "100000000");
            }
        }
    }
    public String generate() {
        try (Jedis jedis = jedisPool.getResource()) {
            // 起始时间到当前时间的分钟数作为随机因子, 用来减少全是1个数的出现情况
            long value = (System.currentTimeMillis() - epoch) / 60000
                    + jedis.incr(ID_COUNTER_REDISKEY);
            return NICKNAME_PREFIX + String.valueOf(value);
        }
    }
}

你可能感兴趣的:(java)