深入JMS - 2 - 案例入门
前一讲简单的介绍了一下JMS的基本概念, 这一讲结合一个例子让大家深入理解前一讲的基本概念. 首先需要做的是选择一个JMS提供者, 如果在JavaEE环境中可以不用考虑这些. 我们选择ActiveMQ, 官方地址: http://activemq.apache.org/. 网上有很多介绍ActiveMQ的文档, 所以在这里就不介绍了.
按照上一讲的这个简图,
import javax.jms.Connection;import javax.jms.Message;import javax.jms.MessageConsumer;import javax.jms.MessageProducer;import javax.jms.Queue;import javax.jms.Session;import javax.jms.TextMessage;import org.apache.activemq.ActiveMQConnectionFactory;import org.apache.activemq.command.ActiveMQQueue;public class MessageSendAndReceive { public static void main(String[] args) throws Exception { ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); Connection connection = factory.createConnection(); connection.start(); Queue queue = new ActiveMQQueue("testQueue"); final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Message message = session.createTextMessage("Hello JMS!"); MessageProducer producer = session.createProducer(queue); producer.send(message); System.out.println("Send Message Completed!"); MessageConsumer comsumer = session.createConsumer(queue); Message recvMessage = comsumer.receive(); System.out.println(((TextMessage)recvMessage).getText()); }}