Modify the code logic and add a mongo svc context

This commit is contained in:
wwweww
2026-04-25 08:29:25 +08:00
parent 5a99baafd0
commit 2ec2075c16
6 changed files with 103 additions and 265 deletions
+35 -2
View File
@@ -1,22 +1,55 @@
package svc
import (
"context"
"log"
"time"
"juwan-backend/app/chat/api/internal/config"
"juwan-backend/app/chat/chatcore"
"github.com/redis/go-redis/v9"
"github.com/wwweww/go-wst/stateless"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type ServiceContext struct {
Config config.Config
Store *chatcore.Store
Store chatcore.Store
MsgStore *stateless.MemoryStore
}
func NewServiceContext(c config.Config) *ServiceContext {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(c.Mongo.URI))
if err != nil {
log.Fatalf("mongo connect: %v", err)
}
if err := mongoClient.Ping(ctx, nil); err != nil {
log.Fatalf("mongo ping: %v", err)
}
db := mongoClient.Database(c.Mongo.Database)
mongoStore, err := chatcore.NewMongoStore(db)
if err != nil {
log.Fatalf("mongo store: %v", err)
}
rdb := redis.NewClient(&redis.Options{
Addr: c.Redis.Addr,
Password: c.Redis.Password,
DB: c.Redis.DB,
})
if err := rdb.Ping(ctx).Err(); err != nil {
log.Fatalf("redis ping: %v", err)
}
return &ServiceContext{
Config: c,
Store: chatcore.NewStore(),
Store: chatcore.NewCachedStore(mongoStore, rdb),
MsgStore: stateless.NewMemoryStore(),
}
}