Java项目生成唯一有序的编号-使用redis

    项目中有种场景需要生成唯一、有序、自增编号,因为项目是分布式部署,这使得编号的生成有点麻烦。最后在同事的建议下使用Redis的Incrby方法来简洁有效的解决这种问题。

public String generateProtocolNo(String districtCode) {
    try {
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        Long count = jedisClientUtil.hincrBy(RedisKeyGenerator.getProtocolNoSuffix(year), districtCode, 1);
        return districtCode + "-" + year + "-" + String.format("%03d", count);
    } catch (Exception ex) {
        log.error("fail.in.genProjectNo,cause:{}", Throwables.getStackTraceAsString(ex));
        String protocolNo = String.format("%s-%s-%s", districtCode, new SimpleDateFormat("yyyy").format(new Date()), System.currentTimeMillis());
        return protocolNo;
    }
}
  • Redis Incrby 命令用于为哈希表中的字段值加上指定增量值。增量值可以为负数;相当于对指定字段进行减法操作。

具体详情参见文档

你可能感兴趣的:(java)