redis_snowflake

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2024 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

RedisSnowflake

将雪花算法生成分布式id的参数放到Redis中,并采用分布式锁,保证分布式场景下id的正确性

使用

  1. 安装依赖
go get -u github.com/zhanglp0129/redis_snowflake
  1. 创建雪花算法配置
cfg := snowflake.DefaultConfig
startTime, _ := time.Parse("2006-01-02 15:04:05", "2024-08-14 00:00:00")
cfg.SetStartTime(startTime)
  1. 创建redis实例
rdb := redis.NewClient(&redis.Options{
    Addr: "127.0.0.1:6379",
})
defer rdb.Close()
  1. 创建工作节点
// 使用分布式锁保证并发安全
worker, err := redis_snowflake.NewRedisWorker(rdb, "key", "lock-key", cfg, 0)
// 使用lua脚本保证并发安全
worker, err := redis_snowflake.NewRedisWorkerNoLock(rdb, "key", cfg, 0)
  1. 生成id
id, err := worker.GenerateId()

LICENSE

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NewWorkerLuaScript  string
	GenerateIdLuaScript string
)
View Source
var LuaFS embed.FS

Functions

func NewRedisWorker

func NewRedisWorker(rdb redis.UniversalClient, key, lockKey string, config snowflake.SnowFlakeConfig, machineId int64) (snowflake.WorkerInterface, error)

NewRedisWorker 创建一个雪花算法的redis工作节点;rdb,redis实例 key,存储在redis中,雪花id生成参数对应的key;lockKey,分布式锁对应的key; config,雪花算法相关配置;machineId,机器码

func NewRedisWorkerNoLock added in v1.0.1

func NewRedisWorkerNoLock(rdb redis.UniversalClient, key string, config snowflake.SnowFlakeConfig, machineId int64) (snowflake.WorkerInterface, error)

NewRedisWorkerNoLock 创建一个不使用分布式锁的雪花算法redis工作节点;rdb,redis实例 key,存储在redis中,雪花id生成参数对应的key; config,雪花算法相关配置;machineId,机器码

Types

type RedisWorker

type RedisWorker struct {
	// contains filtered or unexported fields
}

func (*RedisWorker) GenerateId

func (w *RedisWorker) GenerateId() (int64, error)

GenerateId 生成雪花id

type RedisWorkerNoLock added in v1.0.1

type RedisWorkerNoLock struct {
	// contains filtered or unexported fields
}

func (*RedisWorkerNoLock) GenerateId added in v1.0.1

func (w *RedisWorkerNoLock) GenerateId() (int64, error)

Jump to

Keyboard shortcuts

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