avatar

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

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

java
1
2
3
4
5
6
7
8
9
10
11
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 Hincrby 命令用于为哈希表中的字段值加上指定增量值。增量值可以为负数;相当于对指定字段进行减法操作。

具体详情参见文档

文章作者: 海东青
文章链接: https://haohaogit.github.io/2020/03/25/%E7%94%9F%E6%88%90%E5%94%AF%E4%B8%80%E6%9C%89%E5%BA%8F%E7%9A%84%E7%BC%96%E5%8F%B7-%E4%BD%BF%E7%94%A8redis/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Hexo
打赏
  • 微信
    微信
  • 支付宝
    支付宝