servicecontext.go 2.8 KB

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