トランザクション・セッション・モードでメッセージを送信/受信する例

2673 ワード

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