3
我想使用Active MQ學習JMS應用程序。
所以下載了apache-activemq-5.5.1並啓動了服務器
並找到了示例代碼但是沒有工作。爲什麼會發生異常?
注:我添加的ActiveMQ庫,我的項目和庫包含org.slf4j模塊使用Active MQ的示例JMS示例
import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.MessageListener;
//JMS Producer
public class JMSProducer {
public void produce() {
String url = "tcp://localhost:61616";
ConnectionFactory factory = new ActiveMQConnectionFactory(url);
try {
Connection connection = factory.createConnection();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("TestTopic");
MessageProducer producer = session.createProducer(topic);
TextMessage msg = session.createTextMessage();
msg.setText("Hello JMS World");
producer.send(msg);
}
catch(JMSException exp) {
}
}
}
//JMS Consumer
public class JMSConsumer {
public void consume() {
String url = "tcp://localhost:61616";
ConnectionFactory factory = new ActiveMQConnectionFactory(url);
try {
Connection connection = factory.createConnection();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("TestTopic");
MessageConsumer consumer = session.createConsumer(topic);
JMSMessageListener listener = new JMSMessageListener();
consumer.setMessageListener(listener);
connection.start();
}
catch(JMSException exp) {
}
}
}
//JMS Message Listener
public class JMSMessageListener implements MessageListener {
@Override
public void onMessage(javax.jms.Message msg) {
System.out.println(msg.toString());
}
}
+1 - 這幫助了我。在嘗試使用JMS的不同方式並且使用比ActiveMQ 5.9.1要求的SLF4J更早版本的glassfish的情況下,有一個pom。註釋掉pom中的glassfish依賴關係導致一切正常。 – rishimaharaj 2014-04-27 04:50:01