恢复数据库对象与redis对象的返回

This commit is contained in:
2025-11-30 16:03:50 +08:00
parent d454d8e143
commit fd37c5c301
4 changed files with 90 additions and 8 deletions

View File

@@ -8,6 +8,7 @@ import (
"time"
"git.toowon.com/jimmy/go-common/factory"
"github.com/redis/go-redis/v9"
)
func main() {
@@ -145,12 +146,12 @@ func main() {
fac.LogInfo("键是否存在: %v", exists)
}
// ========== 数据库操作 ==========
// ========== 数据库操作(黑盒模式,获取对象) ==========
db, err := fac.GetDatabase()
if err != nil {
fac.LogError("数据库连接失败: %v", err)
} else {
// 直接使用GORM
// 直接使用GORM,无需自己实现创建逻辑
var count int64
if err := db.Table("users").Count(&count).Error; err != nil {
fac.LogError("查询用户数量失败: %v", err)
@@ -159,6 +160,27 @@ func main() {
}
}
// ========== Redis操作获取客户端对象黑盒模式 ==========
redisClient, err := fac.GetRedisClient()
if err != nil {
fac.LogError("Redis客户端不可用: %v", err)
} else {
// 直接使用Redis客户端无需自己实现创建逻辑
val, err := redisClient.Get(ctx, "test_key").Result()
if err != nil && err != redis.Nil {
fac.LogError("Redis错误: %v", err)
} else if err == redis.Nil {
fac.LogInfo("Redis键不存在")
} else {
fac.LogInfo("Redis值: %s", val)
}
// 使用高级功能如Hash操作
redisClient.HSet(ctx, "user:123", "name", "John")
name, _ := redisClient.HGet(ctx, "user:123", "name").Result()
fac.LogInfo("Redis Hash值: %s", name)
}
fac.LogInfo("示例执行完成")
}