doujiaci7976 2016-03-10 12:00
浏览 305
已采纳

使用Go-Stomp缓存ActiveMQ的连接

Using Go-Stomp, one can obtain the connection using below code.

if conn, err = stomp.Dial("tcp",
        Broker.URI,
        stomp.ConnOpt.Login(Broker.User, Broker.Password)); err != nil {
        panic(fmt.Sprintf("Could not connect to ActiveMQ using brokerUri %v. Can not continue.", Broker.URI))
    }

Can the connection be cached to reuse to send messages for different requests? Or do we need to obtain the connection each time one wants to send a message?
Later sounds in-efficient.
Send method on the connection instance closes the connection in case of failures. So if we cache it, one has to check if the connection is still live for subsequent send message invocations. But I did not find a method to check if the connection is closed? Conn struct has closed member but this is not exposed via any method.

// A Conn is a connection to a STOMP server. Create a Conn using either
// the Dial or Connect function.
type Conn struct {
    conn         io.ReadWriteCloser
    readCh       chan *frame.Frame
    writeCh      chan writeRequest
    version      Version
    session      string
    server       string
    readTimeout  time.Duration
    writeTimeout time.Duration
    closed       bool
    options      *connOptions
}
  • 写回答

2条回答 默认 最新

  • douhan4812 2016-03-10 13:12
    关注

    I added code to handle failures and check the specific error.

    if err := conn.Send(queue, "text/plain", []byte(message)); err != nil {
                if err == stomp.ErrAlreadyClosed {
                    log.Println("ActiveMQ Connection is in closed state. Reconnecting ...")
                    conn = ConnectToBroker()
                    err = conn.Send(queue, "text/plain", []byte(message))
                }
                if err != nil {
                    log.Printf("Failed to send message to Queue %v.  Error is %v, Payload is %v", queue, err.Error(), message)
                }
                return err
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了