[Yugong Series] October 2023 .NET CORE tool case-DeveloperSharp (distributed unique ID)

About the author, Yu Gong moves the code
“Title”: Huawei Cloud Special Editor, Huawei Cloud Cloud Enjoyment Expert, Huawei Developer Expert, Huawei Product Cloud Testing Expert, CSDN Blog Expert, Alibaba Cloud Expert Blogger, Tencent Cloud Excellent Blogger, Nuggets Excellent Blogger, 51CTO Blogging experts and more.
“Recent Honors”: CSDN Blog Star TOP2 in 2022, Huawei Cloud Top Ten Bloggers in 2022, etc.
“Blog Content”: .NET, Java, Python, Go, Node, front-end, IOS, Android, Hongmeng, Linux, Internet of Things, network security, big data, artificial intelligence, U3D games, small programs and other related field knowledge.
Welcome Like?Comment?Collect

Article directory

  • Foreword
  • 1. Distributed unique ID
    • 1. Installation package
    • 2.Use
    • 3. Custom snowflake algorithm
  • Thank you: a letter to readers

Foreword

Distributed Unique ID (DUID for short) refers to an ID generation method used in distributed systems to avoid ID conflicts.

In a distributed system, multiple nodes generate IDs at the same time. If a single-machine auto-increment sequence is used, it is easy to cause ID duplication problems. In order to solve this problem, the concept of DUID was born.

Common DUID generation methods include:

  1. UUID: Universal Unique Identifier, a standard used by network software to uniquely identify information. UUIDs are generated based on multiple factors such as timestamps, hardware devices, etc., making them very difficult to repeat.

  2. Snowflake algorithm: It is a distributed ID generation algorithm open sourced by Twitter. The ID generated by the Snowflake algorithm is a 64-bit integer, of which 42 bits represent the timestamp, 10 bits represent the worker machine ID, and 12 bits represent the sequence number. This method can ensure the uniqueness of ID in a distributed system.

  3. GUID: Globally Unique Identifier, an algorithm defined by Microsoft to generate unique IDs. Similar to UUID, GUID is also generated based on a variety of parameters and is highly unique.

This article mainly introduces the use of DeveloperSharp. DeveloperSharp is a necessary system platform for R&D of medium and large projects, and it is also a low-code platform.

It mainly includes the following functions:

  • Database operations based on Sql statements, stored procedures, transactions, and paging. And supports almost all types of databases on the market.
  • Picture manipulation. Crop, scale, watermark.
  • http request call (Post and Get)
  • Efficient paging
  • Web service/WebApi load balancing
  • Database load balancing and read-write separation
  • CORS cross-domain access
  • UUID globally unique identifier
  • MQ message queue (please use DeveloperSharp.RabbitMQ package separately)
  • Redis cache (please use DeveloperSharp.Redis package separately)
  • Load balancing of “heterogeneous databases”
  • Other related functions

1. Distributed unique ID

1. Installation package

DeveloperSharp

2.Use

1. WEB project

using DeveloperSharp.Framework.CoreUtility; //Reference the DeveloperSharp package from NuGet
--------------------------

//First perform tool preloading in the Startup.cs or Program.cs file
Services.AddTransient<IUtility, Utility>();
--------------------------

//IU is an IUtility type object obtained through dependency injection in the relevant file.
var Id = IU.GenerateId("Order");//Generate distributed unique Id

2.Console project

using DeveloperSharp.Framework.CoreUtility;//Reference the DeveloperSharp package from NuGet
--------------------------

IUtility IU = new Utility();
var Id = IU.GenerateId("Order");//Generate distributed unique Id

3. Custom snowflake algorithm

The following is a C#-based snowflake algorithm ID generator sample code:

public class SnowflakeIdGenerator
{<!-- -->
    private static readonly long twepoch = 1288834974657L;
    private static readonly long workerIdBits = 5L;
    private static readonly long datacenterIdBits = 5L;
    private static readonly long maxWorkerId = -1L ^ (-1L << (int)workerIdBits);
    private static readonly long maxDatacenterId = -1L ^ (-1L << (int)datacenterIdBits);
    private static readonly long sequenceBits = 12L;

    private static readonly long workerIdShift = sequenceBits;
    private static readonly long datacenterIdShift = sequenceBits + workerIdBits;
    private static readonly long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private static readonly long sequenceMask = -1L ^ (-1L << (int)sequenceBits);

    private static readonly Random random = new Random();

    private readonly long workerId;
    private readonly long datacenterId;
    private long lastTimestamp = -1L;
    private long sequence;

    public SnowflakeIdGenerator(long workerId, long datacenterId)
    {<!-- -->
        if (workerId > maxWorkerId || workerId < 0)
        {<!-- -->
            throw new ArgumentException($"worker Id can't be greater than {<!-- -->maxWorkerId} or less than 0");
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0)
        {<!-- -->
            throw new ArgumentException($"datacenter Id can't be greater than {<!-- -->maxDatacenterId} or less than 0");
        }

        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public longNextId()
    {<!-- -->
        lock(this)
        {<!-- -->
            long timestamp = GetTimestamp();
            if (timestamp < lastTimestamp)
            {<!-- -->
                throw new Exception($"clock moved backwards. Refusing to generate id for {<!-- -->lastTimestamp - timestamp} milliseconds");
            }
            if (lastTimestamp == timestamp)
            {<!-- -->
                sequence = (sequence + 1) & amp; sequenceMask;
                if (sequence == 0)
                {<!-- -->
                    timestamp = TilNextMillis(lastTimestamp);
                }
            }
            else
            {<!-- -->
                sequence = random.Next(1, 10);
            }

            lastTimestamp = timestamp;

            return ((timestamp - twepoch) << (int)timestampLeftShift) |
                    (datacenterId << (int)datacenterIdShift) |
                    (workerId << (int)workerIdShift) |
                    sequence;
        }
    }

    private long TilNextMillis(long lastTimestamp)
    {<!-- -->
        long timestamp = GetTimestamp();
        while (timestamp <= lastTimestamp)
        {<!-- -->
            timestamp = GetTimestamp();
        }
        return timestamp;
    }

    private static long GetTimestamp()
    {<!-- -->
        return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
    }
}

Instructions:

static void Main(string[] args)
{<!-- -->
    SnowflakeIdGenerator generator = new SnowflakeIdGenerator(1, 1);
    long id = generator.NextId();
    Console.WriteLine(id);
}

In this way, a unique ID generated by the snowflake algorithm can be generated.

Thank you: a letter to readers

Dear readers,

I put a lot of thought and time into this article and hope to provide you with valuable content. This article contains in-depth research and personal experience, and I believe this information will be very helpful to you.

If you find this article helpful, I sincerely ask you to consider supporting it with a $1 donation. This amount will not be a burden on your finances, but it will have a positive impact on my ability to continue creating quality content.

I wrote this article because I love sharing useful knowledge and insights. Your support will help me continue this mission and encourage me to spend more time and energy creating more valuable content.

If you would like to support my creation, please scan the QR code below, your support will be greatly appreciated. At the same time, if you have any feedback or suggestions, please share them with me.

Thank you again for reading and supporting!

Sincerest regards, “Yugong moves the code”