在事务性会话模式中发送/接收消息的例子

1、消息发送程序

public class Sender{
	public static void main(String[] args) {
		try{
			new Sender().execute();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void execute() throws Exception {
		//连接工厂
		ConnectionFactory connFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD,
				"tcp://localhost:61616");
		
		//连接到JMS提供者
		Connection conn = connFactory.createConnection();
		conn.start();
		
		//事务性会话,自动确认消息		
		//0-SESSION_TRANSACTED    1-AUTO_ACKNOWLEDGE   		
		//2-CLIENT_ACKNOWLEDGE    3-DUPS_OK_ACKNOWLEDGE
		Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
		
		//消息的目的地
		Destination destination = session.createQueue("queue.hello");
		
		//消息生产者		
		//1-NON_PERSISTENT  2-PERSISTENT
		MessageProducer producer = session.createProducer(destination);
		producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); //不持久化
		
		//创建文本消息
		TextMessage message = session.createTextMessage("Hello ActiveMQ");
		
		//发送消息
		producer.send(message);
		
		session.commit(); //在事务性会话中,只有commit之后,消息才会真正到达目的地
		producer.close();
		session.close();
		conn.close();
	}
}

 

2、消息接收程序

public class Receiver{
	public static void main(String[] args) {
		try{
			new Receiver().execute();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void execute() throws Exception {
		//连接工厂
		ConnectionFactory connFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD,
				"tcp://localhost:61616");
		
		//连接到JMS提供者
		Connection conn = connFactory.createConnection();
		conn.start();
		
		//事务性会话,自动确认消息
		Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
		
		//消息的来源地
		Destination destination = session.createQueue("queue.hello");
		
		//消息消费者
		MessageConsumer consumer = session.createConsumer(destination);
		
		while(true){
			TextMessage message = (TextMessage)consumer.receive(1000); //毫秒数
			session.commit(); //在事务性会话中,接收到消息后必须commit,否则下次启动接收者时还会收到旧数据
			
			if(message!=null){
				System.out.println(message.getText());
			}else{
				break;
			}
		}
		
		consumer.close();
		session.close();
		conn.close();
	}
}

  

你可能感兴趣的:(jms,activemq)