2

I've tried to generate 10k integer from Go's UnixNano, and it doesn't show any collision.

package main

import (
        "fmt"
        "sync"
        "time"
        "strconv"
        "github.com/OneOfOne/cmap"
)

func main() {
        var wg sync.WaitGroup
        k := 1000
        wg.Add(k * 1000)
        coll := cmap.New()
        for z := 0; z < k*1000; z++ {
                go func() {
                        k := strconv.FormatInt(time.Now().UnixNano(),36)
                        if coll.Has(k) {
                                fmt.Println(`collision: `, k)
                        }
                        coll.Set(k,true) 
                        defer wg.Done()
                }()
        }
        wg.Wait()
}

The database only support 64-bit integer at maximum and doesn't support atomic counter/serial.

EDIT 2017-03-06 It has collision

collision:  bb70elvagvqu
collision:  bb70elwbgk98
collision:  bb70elwnxcm7

So if I create a primary key using that number, converted to base-36, appended with 3 digit server key would it be no possible collision right?

Some example:

  0bb4snonc8nfc001 (current time, 1st server)
  1y2p0ij32e8e7zzz (maximum value: 2262-04-11 23:47:16.854775807, 46654th/last server)

Requirement 2017-03-04

  • Lexicographically correct
  • Unique
  • As short as possible
  • Ordered by creation time
Kokizzu
  • 24,974
  • 37
  • 137
  • 233
  • what happens when leap second, or just computer clock was adjusted by ntp? – ymonad Mar 03 '17 at 04:35
  • 1
    Can you use a UUID instead of rolling your own? http://stackoverflow.com/questions/15130321/is-there-a-method-to-generate-a-uuid-with-go-language – stderr Mar 03 '17 at 04:42
  • 1
    This looks like a half implemented snowflake idea to me. Check out https://github.com/bwmarrin/snowflake – tsdtsdtsd Mar 03 '17 at 10:44

1 Answers1

1

You didn't specified which database you want to use, but I suppose to it is MySQL. The best unique ID currently I think is the UUID and the MySQL provide to use it as primary key.

create table users(id varchar(36), name varchar(200));
insert into users values(uuid(), 'Andromeda');

It is provide a unique ID in every cases.

Of course you can use it in every other database, because the Golang and databases supporting it either. You can find many UUID generator on Github for Golang.

PumpkinSeed
  • 2,945
  • 9
  • 36
  • 62