package event_m import ( "gorm.io/gorm" "hilo-user/domain" "hilo-user/resource/mysql" "time" ) // 进房事件消息 type EventGroupIn struct { mysql.Entity *domain.Model `gorm:"-"` Proto mysql.Type Payload []byte Mark mysql.YesNo } // 偏移值 type EventGroupInOffset struct { mysql.Entity *domain.Model `gorm:"-"` MarkOffset mysql.ID } // 获取当前偏移值 func Offset(model *domain.Model) (*EventGroupInOffset, error) { offset := new(EventGroupInOffset) if err := model.Db.WithContext(model).First(offset).Error; err != nil { if err != gorm.ErrRecordNotFound { model.Log.Errorf("Offset fail:%v", err) return nil, err } // gorm.ErrRecordNotFound } offset.Model = model return offset, nil } // 批量获取进房事件 func FetchEventGroupIn(model *domain.Model, limit int) ([]*EventGroupIn, *EventGroupInOffset, error) { offset, err := Offset(model) if err != nil { return nil, nil, err } var events []*EventGroupIn if err := model.Db.WithContext(model).Model(EventGroupIn{}). Where("id > ?", offset.MarkOffset). Order("id asc").Limit(limit).Find(&events).Error; err != nil { model.Log.Errorf("FetchEventGroupIn fail:%v", err) return nil, nil, err } return events, offset, nil } // 标记已完成 func (p *EventGroupIn) MarkDone() error { p.Mark = mysql.YES return p.Db.WithContext(p.Model).Model(EventGroupIn{}).Where("id = ?", p.ID).Update("mark", p.Mark).Limit(1).Error } // 查询过去1小时-5分钟前未mark的事件 // 用来补偿 // 记得加limit func FetchUnMarkEvents(model *domain.Model, limit int) ([]*EventGroupIn, error) { offset, err := Offset(model) if err != nil { return nil, err } t := time.Now().Add(-time.Minute * 5) lt := t.Add(-time.Hour) var events []*EventGroupIn if err := model.Db.WithContext(model).Model(EventGroupIn{}). Where("mark = ?", mysql.NO). Where("id <= ?", offset.MarkOffset). Where("created_time < ?", t). Where("created_time > ?", lt). Order("id asc").Limit(limit).Find(&events).Error; err != nil { model.Log.Errorf("FetchUnMarkEvents fail:%v", err) return nil, err } return events, nil } // 补偿加上unmark的event func AddUnMarkEvent(model *domain.Model, event *EventGroupIn) error { return model.Db.WithContext(model).Create(event).Error }