在项目开发中,我们需要保证数据的唯一性,就目前开发中常用的方式有使用自增序列、GUID、时间戳以及时间戳加上随机数。生成ID的方法有很多,每种适用场景、需求以及性能要求不同。下面我们列出以下较为常用的生成ID的方式,并且来讨论以下他们的优缺点。
TIP:目前有类似GUID的方式,但是大多数都是把时间拼接上去,但是这样就造成了id特别长。
private string GetForeachNumbers(IRedisClient redisClent, ShortNumberType type, int count = 5)
{
var number = string.Empty;
var key = string.Format(CacheKeys.ComShortNumberList, type);
for (var i = 0; i < count; i++)
{
number = redisClent.DequeueItemFromList(key);
if (string.IsNullOrWhiteSpace(number) || string.IsNullOrEmpty(number))
{
if (!RedisUpload(type, true))
{
Thread.Sleep(500);
}
}
else
{
break;
}
}
return number;
}
public bool RedisUpload(ShortNumberType type, bool autoInsert)
{
var result = false;
var key = string.Format(CacheKeys.ComShortNumberList, type);
using (var redisClent = RedisManager.GetClient())
{
if (redisClent.GetListCount(key) <= RedisMinCount)
{
var lockKey = "comShortNumber" + type;
string token;
if (RedisManager.Lock(lockKey, out token, 1500))
{
try
{
var list = GetListForRedis(type);
//存储量不足,自动新增
if (list.Count < RedisUploadCount && autoInsert && AutoInsertList(type))
{
list = GetListForRedis(type);
}
if (list.Any())
{
var ids = list.Select(x => x.Id).ToList();
var numbers = list.Select(x => x.Number).ToList();
UpdateListByStatu(ids, ShortNumberStatus.handleIng);
redisClent.AddRangeToList(key, numbers.OrderByDescending(x => x).ToList());
UpdateListByStatu(ids, ShortNumberStatus.Finished);
}
}
finally
{
RedisManager.DelLock(lockKey, token);
}
result = true;
}
}
else
result = true;
}
return result;
}
public string GetNumber(ShortNumberType type)
{
using (var redisClent = RedisManager.GetClient())
{
return GetForeachNumbers(redisClent, type);
}
}