使用 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 结构具有闭合成员,但这不会通过任何方法公开。
// 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 示例中的示例。
无法测试是否打开。
在库本身中,它们在读取时吃掉错误,但在发送时不吃:
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
}
}