package utils import ( "sync" "time" ) type messageIds struct { ids sync.Map } var MessageIds = new(messageIds) func (t *messageIds) Get(id string) string { v, has := t.ids.Load(id) if !has { return "" } return v.(string) } func (t *messageIds) Set(id, value string) { t.ids.Store(id, value) } func (t *messageIds) Remove(id string) { t.ids.Delete(id) } //数据消息状态管理对象 type MsgStateManage struct { } //数据消息状态管理对象队列 var publicMsgStateList = sync.Map{} //数据消息模型 type MsgState struct { Success bool `json:"success"` State bool `json:"state"` Message string `json:"message"` Value interface{} `json:"value"` Mark string `json:"mark"` } func (t *MsgStateManage) GetMessageStateValue(msgId string) MsgState { o, ok := publicMsgStateList.Load(msgId) var Message MsgState if !ok { return Message } return o.(MsgState) } func (t *MsgStateManage) SetMessageStateValue(msgId string, value MsgState) { publicMsgStateList.Store(msgId, value) } func (t *MsgStateManage) SetMessageStateObj(msgId string, value MsgState) { publicMsgStateList.Store(msgId, value) } func (t *MsgStateManage) RemoveMessageStateObj(msgId string) { publicMsgStateList.Delete(msgId) } func (t *MsgStateManage) HanderMesage(messageId string, timeout int) MsgState { var Message MsgState if timeout <= 0 { timeout = 10 } defer func() { //处理结束,清除本次操作生成的messageId。否则MessageState队列中数据会累积 t.RemoveMessageStateObj(messageId) }() for { if timeout < 1 { if !Message.Success { //等待时间已结束,中台仍未返回结果数据时,自定义消息内容返回给前端 if Message.Message == "" { Message.Message = "数据返回超时" } } //等待时间已结束,强制更改本次操作状态为false.前端通过Success来判断操作是否成功 Message.Success = false return Message } Message = t.GetMessageStateValue(messageId) if Message.State { //中台有返回数据时,直接将结果返回给调用者并结束等待 Message.Success = true return Message } time.Sleep(1 * time.Second) timeout -= 1 } return Message }