You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BookingHeChuan/Myshipping.Application/Helper/SuperShortLinkHelper.cs

120 lines
3.1 KiB
C#

using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Myshipping.Application
{
public class SuperShortLinkHelper
{
10 months ago
private readonly string _base62CharSet = "s9LFkgy5RovixI1aOf8UhdY3r4DMplQZJXPqebE0WSjBn7wVzmN2Gc6THCAKut";
private readonly int _codeLength = 6;
private readonly int _powMax = 62;
10 months ago
public SuperShortLinkHelper()
{
}
/// <summary>
/// 补充0的长度
/// </summary>
private int ZeroLength
{
get
{
return MaxValue.ToString().Length;
}
}
/// <summary>
/// Code长度位数下能达到的最大值
/// </summary>
public long MaxValue
{
get
{
10 months ago
var max = (long)Math.Pow(_powMax, _codeLength) - 1;
return (long)Math.Pow(10, max.ToString().Length - 1) - 1;
}
}
/// <summary>
/// 【混淆加密】转短码
/// 1、根据自增主键id前面补000000123
/// 2、倒转32100000
/// 3、把倒转后的十进制转六十二进制乱序后
/// </summary>
public string Confuse(long id)
{
if (id > MaxValue)
{
throw new Exception($"转换值不能超过最大值{MaxValue}");
}
var idChars = id.ToString()
.PadLeft(ZeroLength, '0')
.ToCharArray()
.Reverse();
var confuseId = long.Parse(string.Join("", idChars));
var base62Str = Encode(confuseId);
return base62Str.PadLeft(_codeLength, _base62CharSet.First());
}
/// <summary>
/// 十进制 -> 62进制
/// </summary>
public string Encode(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException("value", "value must be greater or equal to zero");
var sb = new StringBuilder();
do
{
10 months ago
sb.Insert(0, _base62CharSet[(int)(value % _powMax)]);
value /= _powMax;
} while (value > 0);
return sb.ToString();
}
}
public class ShortLinkOptions
{
public const string SectionName = "ShortShareLink";
/// <summary>
/// 短码长度
/// </summary>
[Range(1, int.MaxValue)]
public int CodeLength { get; set; }
/// <summary>
/// 62位加密秘钥
/// </summary>
[Required]
public string Secrect { get; set; }
/// <summary>
/// 缓存数量限制
/// </summary>
public int? CacheCountLimit { get; set; }
/// <summary>
/// 生成默认数据
/// </summary>
public static ShortLinkOptions GenDefault()
{
return new ShortLinkOptions()
{
CacheCountLimit = 10000
};
}
}
}