对于ConnectionFactory类,方法createConnection()未定义

时间:2014-09-19 05:56:04

标签: java jms activemq

我一直在努力学习ActiveMQ和JMS。当我编译以下代码时,我得到上述异常。虽然,我已经为JMS和ActiveMQ附加了正确的jar文件。当我尝试使用ConnectionFactory对象创建连接(即connectionFactory.createConnection())时,Eclipse要求我向ConnectionFactory对象添加一个强制转换。我在互联网上到处看到的代码与我写的相同。

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class JMSProducer {
public static void main(String[] args) {
     try {
         // Create a ConnectionFactory
         ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("admin", "admin",       

ActiveMQConnection.DEFAULT_BROKER_URL);
         // Create a Connection

         Connection connection = connectionFactory.createConnection();
         //Error seen in above line
         connection.start();
         // Create a Session
         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
         // Create the destination
         Destination destination = session.createQueue("testQ");
         // Create a MessageProducer from the Session to the Queue
         MessageProducer producer = session.createProducer(destination);
         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
         // Create a messages
         TextMessage message = session.createTextMessage("Helloworld");
         producer.send(message);
         session.close();
         connection.close();
         System.out.println("Message sent");

     }
     catch (Exception e) {
         System.out.println(e);
         e.printStackTrace();
     }
  }
 }

1 个答案:

答案 0 :(得分:0)

Sholud做了ActiveMQConnection connection = connectionFactory.createConnection();而不是Connection connection = connectionFactory.createConnection();.现在代码运行正常。