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

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";

转载于:https://my.oschina.net/hzchenyh/blog/742957

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值