使用 Go-Stomp 为 ActiveMQ 缓存连接
Caching connection for ActiveMQ using Go-Stomp
使用Go-Stomp,可以使用以下代码获取连接。
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))
}
是否可以缓存连接以重复使用以针对不同的请求发送消息?
还是每次发送消息都需要获取连接?
以后听起来效率低下。
连接实例上的 Send 方法会在失败时关闭连接。因此,如果我们对其进行缓存,则必须检查连接是否仍然存在以用于后续的发送消息调用。但是我没有找到检查连接是否关闭的方法? Conn 结构有 closed 成员,但它没有通过任何方法公开。
// 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
}
您可以重用连接直到失败,请参阅 go-stomp 示例中的 example。
打开与否无法测试
在库本身中,他们吃掉了读取时的错误,但不是发送时的错误:
if err != nil {
if err == io.EOF {
log.Println("connection closed:", c.rw.RemoteAddr())
我添加了代码来处理故障并检查具体错误。
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
}
}
使用Go-Stomp,可以使用以下代码获取连接。
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))
}
是否可以缓存连接以重复使用以针对不同的请求发送消息?
还是每次发送消息都需要获取连接?
以后听起来效率低下。
连接实例上的 Send 方法会在失败时关闭连接。因此,如果我们对其进行缓存,则必须检查连接是否仍然存在以用于后续的发送消息调用。但是我没有找到检查连接是否关闭的方法? Conn 结构有 closed 成员,但它没有通过任何方法公开。
// 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
}
您可以重用连接直到失败,请参阅 go-stomp 示例中的 example。
打开与否无法测试
在库本身中,他们吃掉了读取时的错误,但不是发送时的错误:
if err != nil {
if err == io.EOF {
log.Println("connection closed:", c.rw.RemoteAddr())
我添加了代码来处理故障并检查具体错误。
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
}
}