雪花算法方法使用
if (shredConfig.ShredMethod == ShredMethod.Snowflake)
{
//求模方式
var snowflake = RegexUtil.GetSnowflakeNumValue(parameters[shredConfig.ShredPrimary].ToString());
string tableSuffixTemp = "0";
try
{
var dataDate = Convert.ToDateTime(GidSnowflakeUtil.Analyze(Convert.ToInt64(snowflake.SnowflakeId)).DataDate);
tableSuffixTemp = dataDate.ToString(shredConfig.ShredTableFormat) ?? "0";
}
catch (Exception e)
{
tableSuffixTemp = "0";
}
lstGroup.Add(tableSuffixTemp);
parameters["tableSuffixTemp"] = tableSuffixTemp;
}
解析雪花ID
/// <summary>
/// 解析雪花ID
/// </summary>
/// <returns></returns>
public static SnowflakeInfo Analyze(long Id)
{
if (Id < 1000000000000000000) return new SnowflakeInfo
{
DatacenterId = 0,
MachineId = 0,
Sequence = 0
};
StringBuilder sb = new StringBuilder();
var timestamp = (Id >> (int)timestampLeftShift);
var time = Jan1st1970.AddMilliseconds(timestamp + twepoch);
var datacenterId = (Id ^ (timestamp << (int)timestampLeftShift)) >> (int)datacenterIdShift;
var workerId = (Id ^ ((timestamp << (int)timestampLeftShift) | (datacenterId << (int)datacenterIdShift))) >> (int)sequenceBits;
var sequence = Id & sequenceMask;
return new SnowflakeInfo
{
DataDate = time.ToLocalTime(),
DatacenterId = datacenterId,
MachineId = workerId,
Sequence = sequence
};
}
逆向从字符串提取雪花算法需要的ID
#region 获取数据值
/// <summary>
/// 获取数据值 默认0 用于把数据进行分表存储 19位
/// </summary>
/// <param name="data"></param>
/// <param name="len">最大19位</param>
/// <returns></returns>
public static SnowflakeInfo GetSnowflakeNumValue(string data, int len = 19)
{
Regex rx = new Regex(@"\\D+?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (string.IsNullOrEmpty(data))
{
data = "0";
}
string temp = (rx.Replace(data, "").TrimStart('0') ?? "0");
long usedId = 0;
if (string.IsNullOrEmpty(temp))
{
temp = "0";
}
int lenT = temp.Length <= len ? temp.Length : len;
try
{
usedId = Convert.ToInt64(temp.Substring(0, lenT));
}
catch (Exception e)
{
//可能最大值问题
usedId = 0;
//Console.WriteLine($"【{data}】【{temp}】{e.Message}");
}
return new SnowflakeInfo
{
OriginalId = data,
UsedId = usedId,
SnowflakeId = (data.Length == 0 || data.Length < len) ? 0 : usedId
};
}
#endregion
文档更新时间: 2021-09-14 22:17 作者:admin