servicecontext.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package svc
  2. import (
  3. "context"
  4. "fmt"
  5. "slowwild/internal/config"
  6. "slowwild/internal/model"
  7. "time"
  8. "github.com/go-redis/redis/v8"
  9. "gorm.io/driver/mysql"
  10. "gorm.io/gorm"
  11. "gorm.io/gorm/schema"
  12. )
  13. type ServiceContext struct {
  14. Config config.Config
  15. Redis *redis.Client
  16. UserModel *model.UserModel
  17. UserFollowModel *model.UserFollowModel
  18. PostModel *model.PostModel
  19. PostContentModel *model.PostContentModel
  20. TagModel *model.TagModel
  21. MessageModel *model.MessageModel
  22. CommentModel *model.CommentModel
  23. PostActionModel *model.PostActionModel
  24. }
  25. func NewServiceContext(c config.Config) *ServiceContext {
  26. // 初始化Redis客户端
  27. rdb := redis.NewClient(&redis.Options{
  28. Addr: c.RedisConf.Host,
  29. Password: c.RedisConf.Password,
  30. DB: c.RedisConf.DB,
  31. PoolSize: 100, // 连接池大小
  32. MinIdleConns: 10, // 最小空闲连接数
  33. ReadTimeout: 2 * time.Second, // 读取超时
  34. WriteTimeout: 2 * time.Second, // 写入超时
  35. DialTimeout: 2 * time.Second, // 连接超时
  36. })
  37. // 测试Redis连接
  38. ctx := context.Background()
  39. _, err := rdb.Ping(ctx).Result()
  40. if err != nil {
  41. panic(fmt.Sprintf("Redis连接失败: %v", err))
  42. }
  43. db, err := gorm.Open(mysql.Open(c.DB.DataSource), &gorm.Config{
  44. NamingStrategy: schema.NamingStrategy{
  45. TablePrefix: "p_",
  46. SingularTable: true,
  47. },
  48. })
  49. if err != nil {
  50. panic(err)
  51. }
  52. return &ServiceContext{
  53. Config: c,
  54. Redis: rdb,
  55. UserModel: model.NewUserModel(db),
  56. UserFollowModel: model.NewUserFollowModel(db),
  57. PostModel: model.NewPostModel(db, rdb),
  58. PostContentModel: model.NewPostContentModel(db),
  59. TagModel: model.NewTagModel(db, rdb),
  60. MessageModel: model.NewMessageModel(db),
  61. CommentModel: model.NewCommentModel(db, rdb),
  62. PostActionModel: model.NewPostActionModel(db, rdb),
  63. }
  64. }