genid

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2022 License: MIT Imports: 6 Imported by: 0

README

genid

Go Refrence Card Go Passing Card Go Report Card Go Codecov Card Go License Card

一个简单的24位 分布式自增的ID生成器

业务码生成规则如下

业务ID(4位)+时间戳(14位)+自增序列(8位)

如下图: alt

其中inc id 是通过redis 中的原子自增实现的,理论上1s最多可以生成 99999999 个不同的ID

当然这依赖于redis的读写能力,超高并发场景下可将redis做集群化

快速开始

package main

import (
	"context"
	"fmt"

	"github.com/dogslee/genid"
	"github.com/go-redis/redis/v8"
)

func main() {
	cli := redis.NewClient(
		&redis.Options{
			Addr: "127.0.0.1:16379",
		},
	)
	g, err := genid.New(
		genid.DB(15),
		genid.Cli(cli),
	)
	if err != nil {
		panic(err)
	}
	code, _ := g.Create(context.Background(), "1000")
	fmt.Println(code)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Generator

type Generator interface {
	// Creaet create one id code
	Create(ctx context.Context, biz string) (string, error)
	// CreateBatch batch create biz code
	CreateBatch(ctx context.Context, biz string, num int) ([]string, error)
}

Generator id generate interface

func New

func New(opts ...Option) (Generator, error)

New create new genid

type Option

type Option func(o *option)

Option operator the genid

func Cli

func Cli(c *redis.Client) Option

Cli 更改默认redis 连接

func DB

func DB(d int) Option

DB 更改默认redis db

func Exp

func Exp(e int) Option

Exp 更改默认redis过期时间

Jump to

Keyboard shortcuts

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