message_id.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package utils
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type messageIds struct {
  7. ids sync.Map
  8. }
  9. var MessageIds = new(messageIds)
  10. func (t *messageIds) Get(id string) string {
  11. v, has := t.ids.Load(id)
  12. if !has {
  13. return ""
  14. }
  15. return v.(string)
  16. }
  17. func (t *messageIds) Set(id, value string) {
  18. t.ids.Store(id, value)
  19. }
  20. func (t *messageIds) Remove(id string) {
  21. t.ids.Delete(id)
  22. }
  23. //数据消息状态管理对象
  24. type MsgStateManage struct {
  25. }
  26. //数据消息状态管理对象队列
  27. var publicMsgStateList = sync.Map{}
  28. //数据消息模型
  29. type MsgState struct {
  30. Success bool `json:"success"`
  31. State bool `json:"state"`
  32. Message string `json:"message"`
  33. Value interface{} `json:"value"`
  34. Mark string `json:"mark"`
  35. }
  36. func (t *MsgStateManage) GetMessageStateValue(msgId string) MsgState {
  37. o, ok := publicMsgStateList.Load(msgId)
  38. var Message MsgState
  39. if !ok {
  40. return Message
  41. }
  42. return o.(MsgState)
  43. }
  44. func (t *MsgStateManage) SetMessageStateValue(msgId string, value MsgState) {
  45. publicMsgStateList.Store(msgId, value)
  46. }
  47. func (t *MsgStateManage) SetMessageStateObj(msgId string, value MsgState) {
  48. publicMsgStateList.Store(msgId, value)
  49. }
  50. func (t *MsgStateManage) RemoveMessageStateObj(msgId string) {
  51. publicMsgStateList.Delete(msgId)
  52. }
  53. func (t *MsgStateManage) HanderMesage(messageId string, timeout int) MsgState {
  54. var Message MsgState
  55. if timeout <= 0 {
  56. timeout = 10
  57. }
  58. defer func() {
  59. //处理结束,清除本次操作生成的messageId。否则MessageState队列中数据会累积
  60. t.RemoveMessageStateObj(messageId)
  61. }()
  62. for {
  63. if timeout < 1 {
  64. if !Message.Success {
  65. //等待时间已结束,中台仍未返回结果数据时,自定义消息内容返回给前端
  66. if Message.Message == "" {
  67. Message.Message = "数据返回超时"
  68. }
  69. }
  70. //等待时间已结束,强制更改本次操作状态为false.前端通过Success来判断操作是否成功
  71. Message.Success = false
  72. return Message
  73. }
  74. Message = t.GetMessageStateValue(messageId)
  75. if Message.State {
  76. //中台有返回数据时,直接将结果返回给调用者并结束等待
  77. Message.Success = true
  78. return Message
  79. }
  80. time.Sleep(1 * time.Second)
  81. timeout -= 1
  82. }
  83. return Message
  84. }