mirror of
https://github.com/keven1024/015.git
synced 2026-05-26 07:08:02 +00:00
feat(pkg): add async queue and Redis client utilities, implement environment variable management with viper
This commit is contained in:
21
pkg/utils/asyncq.go
Normal file
21
pkg/utils/asyncq.go
Normal 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
53
pkg/utils/env.go
Normal 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)
|
||||
}
|
||||
@@ -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
22
pkg/utils/redis.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user