package svc import ( "context" "fmt" "slowwild/internal/config" "slowwild/internal/model" "time" "github.com/go-redis/redis/v8" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/schema" ) type ServiceContext struct { Config config.Config Redis *redis.Client UserModel *model.UserModel UserFollowModel *model.UserFollowModel PostModel *model.PostModel PostContentModel *model.PostContentModel TagModel *model.TagModel MessageModel *model.MessageModel CommentModel *model.CommentModel PostActionModel *model.PostActionModel } func NewServiceContext(c config.Config) *ServiceContext { // 初始化Redis客户端 rdb := redis.NewClient(&redis.Options{ Addr: c.RedisConf.Host, Password: c.RedisConf.Password, DB: c.RedisConf.DB, PoolSize: 100, // 连接池大小 MinIdleConns: 10, // 最小空闲连接数 ReadTimeout: 2 * time.Second, // 读取超时 WriteTimeout: 2 * time.Second, // 写入超时 DialTimeout: 2 * time.Second, // 连接超时 }) // 测试Redis连接 ctx := context.Background() _, err := rdb.Ping(ctx).Result() if err != nil { panic(fmt.Sprintf("Redis连接失败: %v", err)) } db, err := gorm.Open(mysql.Open(c.DB.DataSource), &gorm.Config{ NamingStrategy: schema.NamingStrategy{ TablePrefix: "p_", SingularTable: true, }, }) if err != nil { panic(err) } return &ServiceContext{ Config: c, Redis: rdb, UserModel: model.NewUserModel(db), UserFollowModel: model.NewUserFollowModel(db), PostModel: model.NewPostModel(db, rdb), PostContentModel: model.NewPostContentModel(db), TagModel: model.NewTagModel(db, rdb), MessageModel: model.NewMessageModel(db), CommentModel: model.NewCommentModel(db, rdb), PostActionModel: model.NewPostActionModel(db, rdb), } }