I just started with the ActiveMQ thing and got several questions.
I should send messages using ActiveMQ
What I did for now :
public class ActiveMQSender
{
private readonly Uri connectionUri;
private readonly IConnectionFactory connectionFactory;
private readonly string destinationName;
public ActiveMQSender()
{
this.connectionUri = new Uri("activemq:tcp://localhost:61616");
this.connectionFactory = new NMSConnectionFactory(this.connectionUri);
this.destinationName = "queue://testQ";
}
public void Send(string msg)
{
using (var connection = this.connectionFactory.CreateConnection())
using (var session = connection.CreateSession())
{
var destination = SessionUtil.GetDestination(session, this.destinationName);
using (var producer = session.CreateProducer(destination))
{
connection.Start();
var message = session.CreateTextMessage(msg);
producer.Send(message);
}
}
}
}
There will be only one instance of this class which will be injected as a constructor parameter.
I am affraid of overhead for connection, session and producer creation, because messages will be sent frequently (often than one message per 10 seconds) Should I reuse connection, session or producer instances, and how should I react to the connection failures? What is the common pattern in such scenarios?
NMS.ActiveMQ like the java client provides a failover transport which will automatically attempt to reconnect to the broker should the connection be lost. You can use that to minimize you failure handling code. Do some Google searching on the topic of failover transport in AMQ.
Recreating the connection and associated resources is not a lightweight operation so you're best bet is to cache them and reuse them for as long as you need that connection. In combination with failover you can reliably reuse the same MessageProducer over and over.
The model of NMS is much the same as JMS so doing some reading on JMS should provide enlightening.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With