Redis递增序列的实现

这个比较简单,我直接上代码了:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

private String getSn(String typeId, String typePrefix) {
    String key = String.format("CommonMaterialService:createCommonMaterial:%s", typePrefix);

    String sn = String.format("%s-%06d", typePrefix, stringRedisTemplate.opsForValue().increment(key, 1));

    LambdaQueryWrapper<CommonMaterial> queryWrapper = new LambdaQueryWrapper<CommonMaterial>()
            .eq(CommonMaterial::getTypeId, typeId)
            .eq(CommonMaterial::getSn, sn);

    List<CommonMaterial> commonMaterials = commonMaterialMapper.selectList(queryWrapper);

    while (commonMaterials != null && commonMaterials.size() != 0) {
        sn = String.format("%s-%06d", typePrefix, stringRedisTemplate.opsForValue().increment(key, 1));

        queryWrapper.eq(CommonMaterial::getSn, sn);

        commonMaterials = commonMaterialMapper.selectList(queryWrapper);
    }

    return sn;
}

参考资料

  1. Redis生成唯一递增序列号~