mq.go 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package mq
  2. import (
  3. "errors"
  4. "fmt"
  5. "mtp20access/client"
  6. "mtp20access/global"
  7. commonRequest "mtp20access/model/common/request"
  8. rsp "mtp20access/model/common/response"
  9. "mtp20access/model/mq/request"
  10. "mtp20access/model/mq/response"
  11. "mtp20access/rabbitmq"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. "go.uber.org/zap"
  15. )
  16. // SendMQ 向总线发送信息
  17. func SendMQ(c *gin.Context, req *request.MQBodyReq) (err error) {
  18. // 获取请求账号信息
  19. s, exists := c.Get("claims")
  20. if !exists {
  21. err = errors.New("获取请求账号信息异常")
  22. global.M2A_LOG.Error(err.Error(), zap.Error(err))
  23. return
  24. }
  25. claims := s.(*commonRequest.CustomClaims)
  26. // 获取登录账户信息
  27. t, exists := client.Clients[claims.SessionID]
  28. if !exists {
  29. err = errors.New("获取登录账户信息异常")
  30. global.M2A_LOG.Error(err.Error(), zap.Error(err))
  31. return
  32. }
  33. // 将客户端请求的数据转换成总线使用的Protobuf
  34. serialNumber := t.GetSerialNumber()
  35. bytes, err := req.GetProtoBytes(&serialNumber)
  36. if err != nil {
  37. return
  38. }
  39. if bytes == nil {
  40. err = errors.New("请求信息序列化失败")
  41. return
  42. }
  43. // 创建异步任务
  44. key := fmt.Sprintf("%v_%v_%v", t.SessionID, req.FunCodeRsp, serialNumber)
  45. // 银行服务相关的回复流水号是错误的,所以需要特殊处理
  46. if int(req.FunCodeReq) == global.T2bBankSignReq ||
  47. int(req.FunCodeReq) == global.T2bBankCancelSignReq ||
  48. int(req.FunCodeReq) == global.T2bBankWithdrawReq ||
  49. int(req.FunCodeReq) == global.T2bBankDepositReq {
  50. key = fmt.Sprintf("%v_%v", t.SessionID, req.FunCodeRsp)
  51. }
  52. asyncTask := client.AsyncTask{
  53. FuncodeRsp: req.FunCodeRsp,
  54. SerialNumber: serialNumber,
  55. Own: t,
  56. IsEncrypted: *req.IsEncrypted,
  57. }
  58. t.SetAsyncTask(&asyncTask, key)
  59. // 获取对应主题
  60. // topic, exists := global.M2A_FuncodeTopic[int(req.FunCodeReq)]
  61. topic := global.GetTopic(int(req.FunCodeReq))
  62. if topic == "" {
  63. global.M2A_LOG.Error(err.Error(), zap.Error(err))
  64. return
  65. }
  66. // 向总线发送业务信息
  67. packet := &client.MQPacket{
  68. FunCode: req.FunCodeReq,
  69. SessionId: uint32(claims.SessionID),
  70. Data: bytes,
  71. }
  72. go rabbitmq.Publish(topic, packet)
  73. global.M2A_LOG.Info("[C->S]", zap.Any("req", req.FunCodeReq), zap.Any("SessionId", packet.SessionId), zap.Any("data", req.Data))
  74. // 阻塞线程等待总线回复或超时
  75. // 这里make时没有指定长度,所以是发送者与接收者的同步操作,发送者会阻塞,所以一般会在下面使用超时来解锁。
  76. asyncTask.Rsp = make(chan response.MQBodyRsp)
  77. select {
  78. case r := <-asyncTask.Rsp: // 总线回复
  79. rsp.OkWithData(r, c)
  80. case <-time.After(time.Second * 30): // 超时
  81. // 删除对应异步任务
  82. t.DeleteAsyncTask(key)
  83. rsp.FailWithMessage("业务超时", c)
  84. }
  85. asyncTask.Finish()
  86. return
  87. }