IdGenerator.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Ant.Core.Utils
  7. {
  8. public class IdGenerator
  9. {
  10. #region Fields
  11. private static readonly string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  12. private static readonly char[] characters = digits.ToCharArray();
  13. private static Random random = new Random();
  14. private static readonly long startTicks = new DateTime(2017, 1, 1).Ticks;
  15. #endregion Fields
  16. /// <summary>
  17. /// Generate a short id
  18. /// </summary>
  19. /// <returns></returns>
  20. public static string NewId()
  21. {
  22. long current = DateTime.Now.Ticks - startTicks;
  23. string strRadix = ConvertToRadix(current, characters.Length);
  24. StringBuilder sb = new StringBuilder(strRadix);
  25. for (int i = 0; i < 6; i++)
  26. {
  27. sb.Append(characters[random.Next(characters.Length)]);
  28. }
  29. return sb.ToString().ToUpper();
  30. }
  31. public static string NewId(string prefix)
  32. {
  33. return $"{prefix}{NewId()}";
  34. }
  35. public static Guid NewGUId()
  36. {
  37. return Guid.NewGuid();
  38. }
  39. public static string NewUUId()
  40. {
  41. return Guid.NewGuid().ToString("N");
  42. }
  43. /// <summary>
  44. /// 生成Token
  45. /// </summary>
  46. /// <returns></returns>
  47. public static string AntToken()
  48. {
  49. return NewUUId().Replace("-", "").ToUpper();
  50. }
  51. private static string ConvertToRadix(long value, int radix)
  52. {
  53. StringBuilder sb = new StringBuilder();
  54. while (value > 0)
  55. {
  56. sb.Insert(0, characters[value % radix]);
  57. value /= radix;
  58. }
  59. return sb.ToString();
  60. }
  61. }
  62. }