feat(pkg): add async queue and Redis client utilities, implement environment variable management with viper

This commit is contained in:
keven1024
2025-12-14 16:25:20 +08:00
parent 18a74b6545
commit 675a6e860a
4 changed files with 97 additions and 1 deletions

21
pkg/utils/asyncq.go Normal file
View File

@@ -0,0 +1,21 @@
package utils
import "github.com/hibiken/asynq"
func GetQueueClient() *asynq.Client {
opt := RedisURI2AsynqOpt(GetEnv("redis.url"))
return asynq.NewClient(opt)
}
func GetQueueInspector() *asynq.Inspector {
opt := RedisURI2AsynqOpt(GetEnv("redis.url"))
return asynq.NewInspector(opt)
}
func RedisURI2AsynqOpt(uri string) asynq.RedisConnOpt {
opt, err := asynq.ParseRedisURI(GetEnv("redis.url"))
if err != nil {
panic(err)
}
return opt
}

53
pkg/utils/env.go Normal file
View File

@@ -0,0 +1,53 @@
package utils
import (
"strings"
"github.com/spf13/viper"
)
var v *viper.Viper
func init() {
InitEnv()
}
func InitEnv() {
if v != nil {
return
}
v = viper.New()
v.SetConfigName("config.yaml")
v.SetConfigType("yaml")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AddConfigPath(".")
v.AddConfigPath("../")
v.AutomaticEnv()
v.WatchConfig()
err := v.ReadInConfig()
if err != nil {
panic(err)
// if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
// // 只有当错误不是"配置文件未找到"时才 panic
// panic(err)
// }
}
}
func GetEnv(key string) string {
InitEnv()
return v.GetString(key)
}
func GetEnvWithDefault(key string, defaultValue string) string {
value := v.GetString(key)
if value == "" {
return defaultValue
}
return value
}
func GetEnvMapString(key string) map[string]string {
InitEnv()
return v.GetStringMapString(key)
}

View File

@@ -1,6 +1,6 @@
module pkg/utils
go 1.23.0
go 1.25.5
toolchain go1.24.11

22
pkg/utils/redis.go Normal file
View File

@@ -0,0 +1,22 @@
package utils
import (
"context"
"github.com/redis/go-redis/v9"
)
var rdb *redis.Client = InitRedis()
var ctx = context.Background()
func InitRedis() *redis.Client {
opt, err := redis.ParseURL(GetEnv("redis.url"))
if err != nil {
panic(err)
}
return redis.NewClient(opt)
}
func GetRedisClient() (*redis.Client, context.Context) {
return rdb, ctx
}