Skip to content

Commit

Permalink
refactor: 重构初始化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
SugarMGP committed Nov 26, 2024
1 parent cdcda1b commit 9f2b84b
Show file tree
Hide file tree
Showing 16 changed files with 74 additions and 251 deletions.
10 changes: 5 additions & 5 deletions app/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var ctx = context.Background()

// getConfig 从 Redis 获取配置,如果不存在则从数据库中获取,并缓存到 Redis
func getConfig(key string) string {
val, err := redis.RedisClient.Get(ctx, key).Result()
val, err := redis.GlobalClient.Get(ctx, key).Result()
if err == nil {
return val
}
Expand All @@ -27,13 +27,13 @@ func getConfig(key string) string {
Key: key,
}).First(&config)

redis.RedisClient.Set(ctx, key, config.Value, 0)
redis.GlobalClient.Set(ctx, key, config.Value, 0)
return config.Value
}

// setConfig 设置指定的配置项,如果不存在则创建新的配置。
func setConfig(key, value string) error {
redis.RedisClient.Set(ctx, key, value, 0)
redis.GlobalClient.Set(ctx, key, value, 0)
var config models.Config
result := database.DB.Where("`key` = ?", key).First(&config)
if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {
Expand All @@ -56,12 +56,12 @@ func setConfig(key, value string) error {

// checkConfig 检查指定的配置项是否存在于 Redis 中。
func checkConfig(key string) bool {
intCmd := redis.RedisClient.Exists(ctx, key)
intCmd := redis.GlobalClient.Exists(ctx, key)
return intCmd.Val() == 1
}

func delConfig(key string) error {
redis.RedisClient.Del(ctx, key)
redis.GlobalClient.Del(ctx, key)
res := database.DB.Where(&models.Config{
Key: key,
}).Delete(models.Config{})
Expand Down
4 changes: 0 additions & 4 deletions app/utils/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,6 @@ func createEncoder(cfg *Config) zapcore.Encoder {

// addAdditionalOptions 添加额外的选项
func addAdditionalOptions(cfg *Config, options *[]zap.Option) {
if !cfg.DisableCaller {
*options = append(*options, zap.AddCallerSkip(1)) // 添加调用方要求
*options = append(*options, zap.AddCaller()) // 添加调用方信息
}
if !cfg.DisableStacktrace {
*options = append(*options, zap.AddStacktrace(zapcore.ErrorLevel)) // 添加堆栈跟踪
}
Expand Down
25 changes: 11 additions & 14 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,18 @@ database:

session:
name: 4u-session
driver: redis
secret: secret

redis:
host: "127.0.0.1"
port: 6379
db: 0
user: root
pass:

wechat: # 微信小程序相关配置 (切记不能泄漏,不能为空)
appid:
appsecret:


user:
host:

Expand All @@ -34,21 +32,20 @@ admin:
minio: # minio 存储配置
accessKey: # 用于身份验证的访问密钥
secretKey: # 用于身份验证的秘密密钥
secure: False # 是否使用 HTTPS,false 表示使用 HTTP
secure: false # 是否使用 HTTPS,false 表示使用 HTTP
endPoint: 127.0.0.1:9000 # MinIO 服务的地址和端口
bucket: 4uonline # 用于存储对象的桶名称
domain: http://127.0.0.1:9000/ # 对外访问的域名
tempDir: tmp # 临时对象存放目录名

log:
development: true # 是否开启开发模式 true: 开启 false: 关闭
disableCaller: false # 是否禁用调用方
development: true # 是否开启开发模式 true: 开启 false: 关闭
disableStacktrace: false # 是否禁用堆栈跟踪
encoding: "json" # 编码格式 json: json格式 console: 控制台格式
level: "info" # 日志级别 debug: 调试 info: 信息 warn: 警告 error: 错误 dpanic: 严重 panic: 恐慌 fatal: 致命
name: "4u" # 日志名称
writers: "console,file" # 日志输出方式 console: 控制台 file: 文件
loggerDir: "./logs" # 日志目录
logMaxSize: 10 # 单个日志文件最大大小 单位: MB
logMaxAge: 7 # 日志保留天数
logCompress: false # 是否压缩日志文件
encoding: "json" # 编码格式 json: json格式 console: 控制台格式
level: "info" # 日志级别 debug: 调试 info: 信息 warn: 警告 error: 错误 dpanic: 严重 panic: 恐慌 fatal: 致命
name: "4u" # 日志名称
writers: "console,file" # 日志输出方式 console: 控制台 file: 文件
loggerDir: "./logs" # 日志目录
logMaxSize: 10 # 单个日志文件最大大小 单位: MB
logMaxAge: 7 # 日志保留天数
logCompress: false # 是否压缩日志文件
1 change: 0 additions & 1 deletion config/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ func init() {
Config.SetConfigName("config")
Config.SetConfigType("yaml")
Config.AddConfigPath(".")
Config.WatchConfig() // 自动将配置读入Config变量
err := Config.ReadInConfig()
if err != nil {
log.Fatal("Config not find", err)
Expand Down
25 changes: 0 additions & 25 deletions config/redis/config.go

This file was deleted.

28 changes: 18 additions & 10 deletions config/redis/redis.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package redis

import "github.com/go-redis/redis/v8"
import (
"4u-go/config/config"
"github.com/go-redis/redis/v8"
)

// redisConfig 定义 Redis 数据库的配置结构体
type redisConfig struct {
Expand All @@ -10,20 +13,25 @@ type redisConfig struct {
Password string
}

// RedisClient 是全局的 Redis 客户端实例
var RedisClient *redis.Client
// GlobalClient 全局 Redis 客户端实例
var GlobalClient *redis.Client

// RedisInfo 保存当前 Redis 配置信息
var RedisInfo redisConfig
// InfoConfig 保存 Redis 配置信息
var InfoConfig redisConfig

// init 函数用于初始化 Redis 客户端和配置信息
func init() {
info := getConfig()
// Init 函数用于初始化 Redis 客户端和配置信息
func Init() {
info := redisConfig{
Host: config.Config.GetString("redis.host"),
Port: config.Config.GetString("redis.port"),
DB: config.Config.GetInt("redis.db"),
Password: config.Config.GetString("redis.pass"),
}

RedisClient = redis.NewClient(&redis.Options{
GlobalClient = redis.NewClient(&redis.Options{
Addr: info.Host + ":" + info.Port,
Password: info.Password,
DB: info.DB,
})
RedisInfo = info
InfoConfig = info
}
61 changes: 0 additions & 61 deletions config/session/config.go

This file was deleted.

12 changes: 0 additions & 12 deletions config/session/memory.go

This file was deleted.

26 changes: 0 additions & 26 deletions config/session/redis.go

This file was deleted.

30 changes: 19 additions & 11 deletions config/session/session.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
package session

import (
"errors"
"fmt"
"strconv"

"4u-go/config/config"
"4u-go/config/redis"
"github.com/gin-contrib/sessions"
sessionRedis "github.com/gin-contrib/sessions/redis"
"github.com/gin-gonic/gin"
)

// Init 初始化会话管理,设置会话存储驱动
// Init 使用 Redis 初始化会话管理
func Init(r *gin.Engine) error {
config := getConfig()
switch config.Driver {
case Redis:
return setRedis(r, config.Name)
case Memory:
setMemory(r, config.Name)
default:
return errors.New("session config error")
}
info := redis.InfoConfig
name := config.Config.GetString("session.name")
secret := config.Config.GetString("session.secret")

store, err := sessionRedis.NewStoreWithDB(10, "tcp",
info.Host+":"+info.Port, info.Password,
strconv.Itoa(info.DB),
[]byte(secret),
)
if err != nil {
return fmt.Errorf("session init failed: %w", err)
}
r.Use(sessions.Sessions(name, store))
return nil
}
32 changes: 0 additions & 32 deletions config/wechat/config.go

This file was deleted.

19 changes: 0 additions & 19 deletions config/wechat/redis.go

This file was deleted.

Loading

0 comments on commit 9f2b84b

Please sign in to comment.