package redis import ( "context" "encoding/json" "fwh-toolbox-server/cache" "time" "go.uber.org/zap" ) var ( aiChatCtx = context.Background() aiChatSessionKey = "fwhtoolbox:aiChat:session:" // {prefix}{userId} → sessionId aiChatSessionListKey = "fwhtoolbox:aiChat:sessionList:" // {prefix}{userId} → JSON array aiChatTTL = 7 * 24 * time.Hour ) // AiSessionItem 会话列表项(Redis 存储结构) type AiSessionItem struct { SessionId string `json:"sessionId"` Title string `json:"title"` CreatedAt int64 `json:"createdAt"` LastActive int64 `json:"lastActive"` } // ============ 当前活跃会话 ============ // AiActiveSession 当前活跃会话信息(Redis 存储结构) type AiActiveSession struct { SessionId string `json:"sessionId"` Title string `json:"title"` CreatedAt int64 `json:"createdAt"` LastActive int64 `json:"lastActive"` } // SaveAiSession 保存用户当前活跃会话完整信息 func SaveAiSession(userId string, sess AiActiveSession) error { key := aiChatSessionKey + userId data, err := json.Marshal(sess) if err != nil { return err } return cache.Set(aiChatCtx, key, string(data), aiChatTTL) } // GetAiSession 获取用户保存的活跃会话信息 func GetAiSession(userId string) (*AiActiveSession, error) { key := aiChatSessionKey + userId raw, err := cache.Get(aiChatCtx, key) if err != nil { return nil, err } var sess AiActiveSession if err := json.Unmarshal([]byte(raw), &sess); err != nil { return nil, err } return &sess, nil } // DeleteAiSession 删除用户保存的活跃会话信息 func DeleteAiSession(userId string) { key := aiChatSessionKey + userId cache.Delete(aiChatCtx, key) } // ============ 会话历史列表 ============ // SaveAiSessionList 保存用户完整会话历史列表 func SaveAiSessionList(userId string, list []AiSessionItem) error { key := aiChatSessionListKey + userId data, err := json.Marshal(list) if err != nil { return err } return cache.Set(aiChatCtx, key, string(data), aiChatTTL) } // GetAiSessionList 获取用户完整会话历史列表 func GetAiSessionList(userId string) ([]AiSessionItem, error) { key := aiChatSessionListKey + userId raw, err := cache.Get(aiChatCtx, key) if err != nil { return nil, err } var list []AiSessionItem if err := json.Unmarshal([]byte(raw), &list); err != nil { return nil, err } return list, nil } // DeleteAiSessionList 删除用户会话历史列表 func DeleteAiSessionList(userId string) { key := aiChatSessionListKey + userId cache.Delete(aiChatCtx, key) } // UpdateAiSessionTitle 更新列表中指定会话的标题 func UpdateAiSessionTitle(userId string, sessionId string, title string) { list, err := GetAiSessionList(userId) if err != nil { return } for i := range list { if list[i].SessionId == sessionId { list[i].Title = title break } } if err := SaveAiSessionList(userId, list); err != nil { zap.L().Warn("[AIChat] 更新会话标题到Redis失败", zap.Error(err)) } }