ActiveMQ支持生产者以同步或异步模式发送消息。使用不同的模式对send方法的反应时间有巨大的影响,反映时间是衡量ActiveMQ吞吐量的重要因素,使用异步发送可以提高系统的性能。
###生产者发送消息 在默认大多数情况 下,AcitveMQ是以异步模式发送消息。
例外的情况: 没有使用事务并且 生产者以PERSISTENT传送模式发送消息。
在这种情况 下, send方法都是同步的,并且一直阻塞直到ActiveMQ发回确认消息:消息已经存储在持久性数据存储中。这种确认机制保证消息不会丢失,但会造成 生产者阻塞从而影响反应时间。
高性能的程序一般都能容忍在故障情况下丢失少量数据。如果编写这样的程序,可以通过使用异步发送来提高吞吐量(甚至在使用PERSISTENT传送模式的情况下)。
####同步发送消息
ConnectionFactory connectionFactory; //连接工厂
Connection connection = null; //连接
Session session; //会话,接收或者发送消息的线程
Destination destination; //消息的目的地
MessageProducer messageProducer; //消息生产者
connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, brokerURL);
try {
connection = connectionFactory.createConnection();
connection.start(); //启动连接
//重点:不使用事务
session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(QueueName); //创建队列
messageProducer = session.createProducer(destination); //创建消息生产者
messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
sendMessage(session, messageProducer);
} catch (JMSException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(connection != null){
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
####异步发送消息
ConnectionFactory connectionFactory; //连接工厂
Connection connection = null; //连接
Session session; //会话,接收或者发送消息的线程
Destination destination; //消息的目的地
MessageProducer messageProducer; //消息生产者
connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, brokerURL);
try {
connection = connectionFactory.createConnection();
connection.start(); //启动连接
//重点:使用事务
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(QueueName); //创建队列
messageProducer = session.createProducer(destination); //创建消息生产者
messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
sendMessage(session, messageProducer);
//重点:需要commit
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(connection != null){
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
异步发送的方式不止以上一种,还有其他好几种,比如通过URL方式也可以,在url后追加 jms.useAsyncSend=true
private static final String brokerURL = "tcp://192.168.10.55:61616?jms.useAsyncSend=true";