ActiveMQ生产者以同步和异步方式发送消息

ActiveMQ支持生产者以同步或异步模式发送消息。使用不一样的模式对send方法的反应时间有巨大的影响,反映时间是衡量ActiveMQ吞吐量的重要因素,使用异步发送能够提升系统的性能。session

###生产者发送消息 在默认大多数状况 下,AcitveMQ是以异步模式发送消息。异步

例外的状况: 没有使用事务而且 生产者以PERSISTENT传送模式发送消息tcp

在这种状况 下, send方法都是同步的,而且一直阻塞直到ActiveMQ发回确认消息:消息已经存储在持久性数据存储中。这种确认机制保证消息不会丢失,但会形成 生产者阻塞从而影响反应时间。性能

高性能的程序通常都能容忍在故障状况下丢失少许数据。若是编写这样的程序,能够经过使用异步发送来提升吞吐量(甚至在使用PERSISTENT传送模式的状况下)。url

####同步发送消息线程

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();
		}
	}
}

####异步发送消息code

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";
相关文章
相关标签/搜索