uid

package
v0.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 29, 2020 License: Apache-2.0 Imports: 1 Imported by: 0

README

Sequence

中文版 English

This module provides the function of generating sequence, and provides the following ways. Users can choose according to their needs

  • mysql
  • redis
  • snowflake

mysql

The generation rule based on MySQL is to use the sequence table in the database to control the auto increment ID, which can ensure the global non auto increment; the generation of sequence strictly depends on MySQL, and the client will get one at a time when using it. The cache range is retrieved after the cache is used, so it can only guarantee that the global self increment cannot guarantee continuity. MySQL mode can provide int32 and Int64 mode sequences, and users can meet their own needs. Specify a different table name. If the provided user has the permission to create a table and modify the parameter autocreatetable = true, the program will automatically create the required sequence table structure

The sequence table structure is as follows. Please initialize it in the database before use

CREATE TABLE `sequence` (
  `id` int(11) NOT NULL,
  `next_id` bigint(20) DEFAULT NULL,
  `cache` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='uid sequence';

How to use

package main
import (
    "fmt"
    "github.com/dbunion/com/uid"
    "time"
)

func main(){
    s, err := uid.NewUID(uid.TypeMySQL, uid.Config{
        Server:          "127.0.0.1",
        Port:            3306,
        User:            "test",
        Password:        "123456",
        InitValue:       time.Now().Unix(),
        Step:            10,
        DBName:          "test",
        TableName:       "int32_seq",
        AutoCreateTable: true,
    })

    if err != nil {
        fmt.Printf("start err:%v\n", err)
        return
    }

   if s.HasInt32() {
        fmt.Printf("Int32:%v\n", s.NextUID32())
   }   
}

redis

The principle of generating sequence in redis is to fix a key and use the incby method to do auto increment. In principle, it can only ensure that the auto increment is discontinuous and the usage method is similar to MySQL. The same can be supported in redis method. The sequence generation of int32 and Int64 needs to use different keys to create different uid objects for processing.

package main
import (
    "fmt"
    "github.com/dbunion/com/uid"
    "time"
)

func main(){
    s, err := uid.NewUID(uid.TypeRedis, uid.Config{
    	Key: "uid", 
        Server: "127.0.0.1", 
        Password: "password",
        Port: 6379,
    })
    
    if err != nil {
        panic(err)
    }

    // gen uid
    for i := 0; i < 10; i++ {
        if s.HasInt32() {
            fmt.Printf("Int32:%d\n", s.NextUID32())
        }
    }
}

SnowFlake

The principle of snowflake algorithm is to use different node ID in different nodes to rely on the globally unique ID generated by snowflake algorithm. Snowflake algorithm can only generate Int64 bit sequence; it cannot provide int32 sequence, Please pay attention to it when using it. The way of using it is similar.

package main
import (
    "fmt"
    "github.com/dbunion/com/uid"
    "time"
)

func main(){
    s, err := uid.NewUID(uid.TypeSnowFlake, uid.Config{
        NodeID: 1,
    })

    if err != nil {
        panic(err)
    }

    // gen uid
    for i := 0; i < 10; i++ {
        fmt.Printf("Int64:%v\n", s.NextUID64())
    }
}

Thanks

This module is completed on the shoulders of the predecessors, integrating the achievements of the predecessors. If there is any infringement or improper use, please inform me in time. Thank you.

  • github.com/go-redis/redis
  • github.com/go-sql-driver/mysql
  • github.com/bwmarrin/snowflake

Documentation

Index

Constants

View Source
const (
	// TypeMySQL - uid use mysql
	TypeMySQL = "mysql"
	// TypeRedis - uid use redis
	TypeRedis = "redis"
	// TypeSnowFlake - uid use snow flake
	TypeSnowFlake = "snow_flake"
)

Variables

This section is empty.

Functions

func Register

func Register(name string, adapter Instance)

Register makes a UID adapter available by the adapter name. If Register is called twice with the same name or if driver is nil, it panics.

Types

type Config

type Config struct {
	// Redis config
	Key string `json:"key"`

	// public param
	Server   string `json:"server"`
	User     string `json:"user"`
	Password string `json:"password"`
	Port     int64  `json:"port"`

	// Snow flake node id
	NodeID int64 `json:"node_id"`

	// Mysql config
	InitValue       int64  `json:"init_value"`
	Step            int64  `json:"step"`
	DBName          string `json:"db_name"`
	TableName       string `json:"table_name"`
	AutoCreateTable bool   `json:"auto_create_table"`

	// Extend fields
	// Extended fields can be used if there is a special implementation
	Extend1 string `json:"extend_1"`
	Extend2 string `json:"extend_2"`
}

Config - uid config

type Instance

type Instance func() UID

Instance is a function create a new UID Instance

type UID

type UID interface {
	// has int32 uid
	HasInt32() bool

	// next int32 uid
	NextUID32() int32

	// next int64 uid
	NextUID64() int64

	// close connection
	Close() error

	// start gc routine based on config settings.
	StartAndGC(config Config) error
}

UID interface contains all behaviors for UID adapter. usage:

uid.Register("uid", uid.NewUID)

func NewUID

func NewUID(adapterName string, config Config) (adapter UID, err error)

NewUID Create a new UID driver by adapter name and config string. config need to be correct JSON as string: {"server": "localhost:9092", "user": "xxxx", "password":"xxxxx"}. it will start gc automatically.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL