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";
相關文章
相關標籤/搜索