go-zero 框架通过内置的 idgen 模块生成雪花算法 id,核心做法是配置 idgen 服务并调用其生成的客户端方法。你需要在 etc 目录下添加配置文件指定 redis 地址和节点 id,然后在代码中实例化 idgen.newclient 并调用 id() 方法即可获取全局唯一的 int64 值。该过程依赖 redis 存储时间戳偏移量,确保分布式环境下的单调递增。

如何配置 idgen 服务的连接参数
配置 idgen 服务需要明确 Redis 的连接信息和当前节点的标识。在 etc 目录创建 idgen.yaml 文件,设置 RedisType 为 redis,填写 RedisHost 和 RedisKey,并分配一个唯一的 NodeID。这些参数决定了 ID 生成的数据源和节点区分方式。

type Config struct {
IdGen idgen.IdGenConf
}
// etc/idgen.yaml
IdGen:
RedisType: redis
RedisHost: 127.0.0.1:6379
RedisKey: snowflake:id
NodeID: 1
如何在业务代码中调用 ID 生成器
在业务逻辑中,通过初始化 idgen.Client 实例并调用 ID() 方法获取 ID。需要在 main.go 或启动入口加载配置,创建客户端后,在业务处理函数中直接调用该方法。返回值为 int64 类型,可直接存入数据库或作为唯一键使用。

package main
import (
"context"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/zrpc"
"net/http"
)
type Config struct {
Rest struct {
Port int
IdGen zrpc.RpcClientConf
}
IdGen struct {
RedisType string
RedisHost string
RedisKey string
NodeID int64
}
}
var client *idgen.IdGenClient
func main() {
var c Config
conf.MustLoad("./config.yaml", &c)
// 初始化 ID 生成客户端
cfg := idgen.IdGenConf{
RedisType: c.IdGen.RedisType,
RedisHost: c.IdGen.RedisHost,
RedisKey: c.IdGen.RedisKey,
NodeID: c.IdGen.NodeID,
}
client = idgen.NewClient(cfg)
server := rest.MustNewServer(c.Rest.RestConf)
defer server.Stop()
handler := func(w http.ResponseWriter, r *http.Request) {
id, err := client.ID(context.Background())
if err != nil {
logx.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write([]byte(idgen.Format(id)))
}
server.AddRoutes(rest.Route{
Method: http.MethodGet,
Path: "/id",
Handler: handler,
})
logx.Infof("Starting server at %d...", c.Rest.Port)
server.Start()
}
当 Redis 连接失败时 ID 生成会返回什么错误
当 Redis 连接失败时,ID() 方法会返回一个非空的 error 对象,且不会生成有效的 ID。此时返回值中的 int64 部分通常为 0 或无效值。错误信息通常包含 "dial tcp" 或 "connection refused" 等网络相关描述,表明无法与 Redis 服务器建立通信以获取时间戳偏移量。


















