package svc import ( "context" "fmt" "slowwild/internal/config" "slowwild/internal/immodel" "slowwild/internal/model" "time" slowWildQueue "git.banshen.xyz/huangguangrong/slow_wild_queue" "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 ChatLogModel immodel.ChatLogModel ConversationModel immodel.ConversationModel ConversationListModel immodel.ConversationListModel MsgPushToClientTransfer slowWildQueue.MsgPushClientTransferClient } 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 { fmt.Println("数据库连接失败", err.Error()) 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), ChatLogModel: immodel.NewChatLogModel(c.Mongo.Url, c.Mongo.Db, c.Mongo.Collection), ConversationModel: immodel.NewConversationModel(c.Mongo.Url, c.Mongo.Db, c.Mongo.Collection), ConversationListModel: immodel.NewConversationListModel(c.Mongo.Url, c.Mongo.Db, c.Mongo.Collection), MsgPushToClientTransfer: slowWildQueue.NewMsgPushClientTransferClient(c.MsgPushToClientTransfer.Addrs, c.MsgPushToClientTransfer.Topic), } }