notice.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package notice
  2. import (
  3. "bp.jydev.jianyu360.cn/BP/jynsq/gonsq"
  4. "encoding/json"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gctx"
  7. "log"
  8. )
  9. type NoticeConfig struct {
  10. IsOpen bool //是否开启提示
  11. IsJsonEncode bool
  12. Address, TopPic string
  13. Id, Title, Text string
  14. }
  15. type Notice struct {
  16. p *gonsq.Producer
  17. c NoticeConfig
  18. }
  19. func NewNotice(c NoticeConfig) (n *Notice, err error) {
  20. if c.IsOpen {
  21. n = &Notice{
  22. c: c,
  23. }
  24. var producer *gonsq.Producer
  25. producer, err = gonsq.NewProducer(c.Address, c.TopPic, c.IsJsonEncode)
  26. if err != nil {
  27. return
  28. }
  29. n.p = producer
  30. }
  31. return nil, nil
  32. }
  33. // SendWarnMsg 发送异常通知
  34. func (n *Notice) SendWarnMsg(detail map[string]interface{}) error {
  35. if n.p == nil {
  36. return nil
  37. }
  38. m := &gonsq.Msg{n.c.Id, n.c.Title, n.c.Text, detail}
  39. bs, err := json.Marshal(m)
  40. if err != nil {
  41. return err
  42. }
  43. g.Log().Debugf(gctx.New(), "模拟发送信息----->", string(bs))
  44. if err := n.p.Publish(bs); err != nil {
  45. log.Println("nsq连接失败", err)
  46. }
  47. return nil
  48. }