IT박스

사람이 읽을 수 있고 사용할 수있는 짧지 만 고유 한 ID 생성

itboxs 2020. 10. 27. 07:58
반응형

사람이 읽을 수 있고 사용할 수있는 짧지 만 고유 한 ID 생성


  • 매일 1000 개 이상이지만 10000 개 미만의 새 레코드를 처리해야 함

  • GUID / UUID, 자동 증가 번호 등을 사용할 수 없습니다.

  • 이상적으로는 5 자 또는 6 자 여야하며 물론 알파도 가능합니다.

  • 가능한 경우 기존의 잘 알려진 알고리즘을 재사용하고 싶습니다.

밖에있는 건 없나요?


Base 62는 tinyurl 및 bit.ly에서 축약 된 URL로 사용됩니다. 사람이 읽을 수있는 "고유 한"ID를 만드는 데있어 잘 알려진 방법입니다. 물론 생성 된 ID를 저장하고 고유성을 보장하기 위해 생성시 중복을 확인해야합니다. (답변 하단의 코드 참조)

기본 62 개의 고유성 메트릭

기본 62의 5 개 문자는 62 ^ 5 개의 고유 ID = 916,132,832 (~ 10 억)를 제공합니다. 하루에 10,000 개의 ID로 9 만 1 천 이상 동안 괜찮습니다.

기본 62의 6 개 문자는 62 ^ 6 개의 고유 ID를 제공합니다. = 56,800,235,584 (560 억 개 이상) 하루에 10,000 개의 ID로 5 백만 일 이상 동안 괜찮습니다.

기본 36 개의 고유성 메트릭

6 개의 문자는 36 ^ 6 개의 고유 ID = 2,176,782,336 (20 억 +)을 제공합니다.

7 개의 문자는 36 ^ 7 개의 고유 ID = 78,364,164,096 (780 억 이상)을 제공합니다.

암호:

public void TestRandomIdGenerator()
{
    // create five IDs of six, base 62 characters
    for (int i=0; i<5; i++) Console.WriteLine(RandomIdGenerator.GetBase62(6));

    // create five IDs of eight base 36 characters
    for (int i=0; i<5; i++) Console.WriteLine(RandomIdGenerator.GetBase36(8));
}

public static class RandomIdGenerator 
{
    private static char[] _base62chars = 
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        .ToCharArray();

    private static Random _random = new Random();

    public static string GetBase62(int length) 
    {
        var sb = new StringBuilder(length);

        for (int i=0; i<length; i++) 
            sb.Append(_base62chars[_random.Next(62)]);

        return sb.ToString();
    }       

    public static string GetBase36(int length) 
    {
        var sb = new StringBuilder(length);

        for (int i=0; i<length; i++) 
            sb.Append(_base62chars[_random.Next(36)]);

        return sb.ToString();
    }
}

산출:

z5KyMg
wd4SUp
uSzQtH
UPrGAT
UIf2IS

QCF9GNM5
0UV3TFSS
3MG91VKP
7NTRF10T
AJK3AJU7

모든 숫자 (예 : DB ID)를 문자열 (솔트 사용)로 변환하는 http://hashids.org/권장 합니다.

이 문자열을 다시 번호로 디코딩 할 수 있습니다. 따라서 데이터베이스에 저장할 필요가 없습니다.

JavaScript, Ruby, Python, Java, Scala, PHP, Perl, Swift, Clojure, Objective-C, C, C ++ 11, Go, Erlang, Lua, Elixir, ColdFusion, Groovy, Kotlin, Nim, VBA, CoffeeScript 및 Node.js 및 .NET 용.


I had similar requirements as the OP. I looked into available libraries but most of them are based on randomness and I didn't want that. I could not really find anything that was not based on random and still very short... So I ended up rolling my own based on the technique Flickr uses, but modified to require less coordination and allow for longer periods offline.

In short:

  • A central server issues ID blocks consisting of 32 IDs each
  • The local ID generator maintains a pool of ID blocks to generate an ID every time one is requested. When the pool runs low it fetches more ID blocks from the server to fill it up again.

Disadvantages:

  • Requires central coordination
  • IDs are more or less predictable (less so than regular DB ids but they aren't random)

Advantages

  • Stays within 53 bits (Javascript / PHP max size for integer numbers)
  • very short IDs
  • Base 36 encoded so very easy for humans to read, write and pronounce
  • IDs can be generated locally for a very long time before needing contact with the server again (depending on pool settings)
  • Theoretically no chance of collissions

I have published both a Javascript library for the client side, as well as a Java EE server implementation. Implementing servers in other languages should be easy as well.

Here are the projects:

suid - Distributed Service-Unique IDs that are short and sweet

suid-server-java - Suid-server implementation for the Java EE technology stack.

Both libraries are available under a liberal Creative Commons open source license. Hoping this may help someone else looking for short unique IDs.


I used base 36 when I solved this problem for an application I was developing a couple of years back. I needed to generate a human readable reasonably unique number (within the current calendar year anyway). I chose to use the time in milliseconds from midnight on Jan 1st of the current year (so each year, the timestamps could duplicate) and convert it to a base 36 number. If the system being developed ran into a fatal issue it generated the base 36 number (7 chars) that was displayed to an end user via the web interface who could then relay the issue encountered (and the number) to a tech support person (who could then use it to find the point in the logs where the stacktrace started). A number like 56af42g7 is infinitely easier for a user to read and relay than a timestamp like 2016-01-21T15:34:29.933-08:00 or a random UUID like 5f0d3e0c-da96-11e5-b5d2-0a1d41d68578.

참고URL : https://stackoverflow.com/questions/9543715/generating-human-readable-usable-short-but-unique-ids

반응형