java操作ActiveMQ

 

package mq;
import javax.jms.Connection;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;


public class Main {

	public static void main(String[] args) throws Exception {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
		Connection conn = factory.createConnection();
		conn.start();
		Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
		Queue query = session.createQueue("my-query");
		MessageProducer producer = session.createProducer(query);
		for (int i = 0; i < 11; i++) {
			TextMessage messgae = session.createTextMessage("Hello World!--"+i);
			producer.send(messgae);
			System.out.println(messgae.getText());
		}
		session.commit();
		session.close();
		conn.close();
	}
}
 

 

package mq;
import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;


public class MainClient {
	public static void main(String[] args) throws Exception {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
		Connection conn = factory.createConnection();
		conn.start();
		Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
		Queue query = session.createQueue("my-query");
		MessageConsumer consumer = session.createConsumer(query);
		int i = 0;
		do {
			TextMessage msg = (TextMessage) consumer.receive(1000);
			if(null==msg||5==i)
				break;
			System.out.println("收到消息:"+msg.getText());
			session.commit();
			i++;
			
		} while (true);
		session.close();
		conn.close();
	}
}
 

你可能感兴趣的:(activemq)