SSE 推送替代轮训

This commit is contained in:
yml2213
2026-05-27 06:18:55 +08:00
parent 1458fc279c
commit a002987784
9 changed files with 493 additions and 42 deletions
+36 -3
View File
@@ -8,6 +8,7 @@ import (
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/chathub"
"golang.org/x/crypto/bcrypt"
"gorm.io/datatypes"
@@ -16,7 +17,8 @@ import (
)
type Repository struct {
db *gorm.DB
db *gorm.DB
hub *chathub.Hub
}
const (
@@ -25,8 +27,8 @@ const (
defaultSupportNickname = "超级管理员"
)
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
func NewRepository(db *gorm.DB, hub *chathub.Hub) *Repository {
return &Repository{db: db, hub: hub}
}
func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatConversation, error) {
@@ -101,6 +103,17 @@ func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatC
return &conversation, nil
}
// NotifyNewConversation 推送群聊创建事件给会话参与者。应在事务提交后调用。
func (r *Repository) NotifyNewConversation(conversationID uint64) {
if r.hub == nil {
return
}
r.hub.NotifyConversation(conversationID, &chathub.ChatEvent{
Type: "conversation_updated",
ConversationID: conversationID,
})
}
func (r *Repository) ListConversations(principal Principal, page, pageSize int) (*PaginatedResult, error) {
page, pageSize = normalizePagination(page, pageSize)
var total int64
@@ -241,6 +254,26 @@ func (r *Repository) SendMessage(principal Principal, conversationID uint64, req
if len(items) == 0 {
return nil, ErrConversationNotFound
}
// 推送新消息事件给会话中的在线参与者
if r.hub != nil {
msg := items[0]
r.hub.NotifyConversation(conversationID, &chathub.ChatEvent{
Type: "new_message",
ConversationID: conversationID,
Message: &chathub.MessageData{
ID: msg.ID,
ConversationID: msg.ConversationID,
SenderType: msg.SenderType,
SenderID: msg.SenderID,
SenderRole: msg.SenderRole,
SenderName: msg.SenderName,
ContentType: msg.ContentType,
Content: msg.Content,
AttachmentURLS: msg.AttachmentURLS,
CreatedAt: msg.CreatedAt.Format(time.RFC3339),
},
})
}
return &items[0], nil
}