简单的JMS示例不会检索JMS消息。为什么呢?

时间:2015-10-07 01:13:41

标签: java jms

请帮忙。这让我伤心了两个星期。

我只想要一个简单的独立Java客户端,它将JMS消息发送到在localhost上运行的glassfish服务器上的JMS队列。并收到它。我似乎无法使这项工作。代码如下。接下来是我从Eclipse工作台运行时获得的控制台输出。

邮件发送时没有错误。 (参见Console中的最后一行)但是监听器从不检索它。谁能帮忙。对于下一个尝试精简JMS的人来说,这真的是一个很好的例子 - 如果它有用的话。有人可以提供帮助吗?

[注意:我使用了大量的print语句来生成下面的控制台输出,但为了便于阅读,我将它们从代码中删除了。我在运行之前清空了glassfish服务器日志。运行后,日志没有添加任何行。]

代码:

public class JMSTest implements MessageListener {

  public static void main(String[] args) {
    JMSTest messageCenter = new JMSTest ();
    messageCenter.sendMessage();
  }

  static final Properties JNDI_PROPERTIES = new Properties() {
    private static final long serialVersionUID = 1L;
      {this.put ("java.naming.factory.initial", "com.sun.jndi.fscontext.RefFSContextFactory");
       this.put ("java.naming.provider.url","file:///C:/glassfish4/mq/opt/java/my_broker");
      }
  };

  String            QUEUE_NAME          = "jms/JMSSendToTestQueue";
  MessageConsumer   msgConsumer         = null;
  MessageProducer   msgProducer         = null;
  ObjectMessage     msg                 = null;
  Connection        connection          = null;

  //constructor
  public JMSTest () {
    try {
/*1*/ Context jndiContext = (Context) new InitialContext(JNDI_PROPERTIES);
/*2*/ ConnectionFactory factory = (ConnectionFactory) jndiContext.lookup("jms/goConnectionFactory");
/*3*/ connection = factory.createConnection();
/*4*/ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
/*5*/ Destination receiveFromDestination = (Destination) jndiContext.lookup(QUEUE_NAME);
/*6*/ this.msgConsumer = session.createConsumer(receiveFromDestination);
/*7*/ this.msgConsumer.setMessageListener(this);
/*8*/ Destination sendToDestination = (Destination) jndiContext.lookup(QUEUE_NAME);
/*9*/ msgProducer = session.createProducer(sendToDestination);
/*10*/this.msg = session.createObjectMessage();
      this.msg.setObject("Hi There. I'm a Test Object.");
    } catch (Exception e) {
      System.out.println("    " + iAmM + "msg: " + e.getMessage());
      e.printStackTrace();
    }
  }

  public void sendMessage() {
    try {
      this.msgProducer.send(this.msg);
      System.out.println("Message Was Sent");
    } catch (JMSException e) {
      System.out.println("Attempt to send message failed.");
      e.printStackTrace();
    }
  }

  public void onMessage(Message msg) {
    System.out.println("TEST MESSAGE RECEIVED");
    if(this.connection!=null) {
      try {
        this.connection.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    try {
      ObjectMessage objMsg = (ObjectMessage) msg;
      System.out.println((String) objMsg.getObject());
    } catch (JMSException e) {
      e.printStackTrace();
    }
  }

控制台:

JMSTest.<init> ()                  beg
    Line 1: InitialContext ok: 
            javax.naming.InitialContext@3b9a45b3

    Line 2: factory is not null: 
      Sun Java System MQ ConnectionFactory
      Class:            com.sun.messaging.ConnectionFactory
      getVERSION():     3.0
      isReadonly():     true
      getProperties():  
        imqOverrideJMSPriority              = false
        imqConsumerFlowLimit                = 1000
        imqOverrideJMSExpiration            = false
        imqAddressListIterations            = 1
        imqLoadMaxToServerSession           = true
        imqConnectionType                   = TCP
        imqPingInterval                     = 30
        imqSetJMSXUserID                    = false
        imqConfiguredClientID               = 
        imqSSLProviderClassname             = com.sun.net.ssl.internal.ssl.Provider
        imqJMSDeliveryMode                  = PERSISTENT
        imqConnectionFlowLimit              = 1000
        imqConnectionURL                    = http://localhost/imq/tunnel
        imqBrokerServiceName                = 
        imqJMSPriority                      = 4
        imqBrokerHostName                   = localhost
        imqJMSExpiration                    = 0
        imqAckOnProduce                     = 
        imqEnableSharedClientID             = false
        imqAckTimeout                       = 0
        imqAckOnAcknowledge                 = 
        imqConsumerFlowThreshold            = 50
        imqDefaultPassword                  = guest
        imqQueueBrowserMaxMessagesPerRetrieve = 1000
        imqDefaultUsername                  = guest
        imqReconnectEnabled                 = false
        imqConnectionFlowCount              = 100
        imqAddressListBehavior              = PRIORITY
        imqReconnectAttempts                = 0
        imqSetJMSXAppID                     = false
        imqConnectionHandler                = com.sun.messaging.jmq.jmsclient.protocol.tcp.TCPStreamHandler
        imqSetJMSXRcvTimestamp              = false
        imqBrokerServicePort                = 0
        imqDisableSetClientID               = false
        imqSetJMSXConsumerTXID              = false
        imqOverrideJMSDeliveryMode          = false
        imqBrokerHostPort                   = 7676
        imqQueueBrowserRetrieveTimeout      = 60000
        imqSetJMSXProducerTXID              = false
        imqSSLIsHostTrusted                 = false
        imqConnectionFlowLimitEnabled       = false
        imqReconnectInterval                = 3000
        imqAddressList                      = 
        imqOverrideJMSHeadersToTemporaryDestinations=false}

    JMSTest.<init> ()                  Line 3: connection is not null:
      BrokerAddress=localhost:7676(60325)
      ConnectionID=967799204788496640
      ReconnectEnabled: false
      IsConnectedToHABroker: false

    JMSTest.<init> ()                  Line 4: session is not null: 
        ConnectionID                        = 967799204788496640
        SessionID                           = 967799204788508160

    JMSTest.<init> ()                  Line 5: receiveFromDestination not null:
      Sun Java System MQ Destination
      getName():        JMSSendToTestQueue
      Class:            com.sun.messaging.Queue
      getVERSION():     3.0
      isReadonly():     false
      getProperties():  
        imqDestinationName                  = JMSSendToTestQueue
        imqDestinationDescription           = A Description for the Destination Object}

    JMSTest.<init> ()                  Line : msgConsumer not null:
        ConnectionID                        = 967799204788496640
        SessionID                           = 967799204788508160
        ConsumerID                          = 967799204788511232
        DestName                            = JMSSendToTestQueue

    JMSTest.<init> ()                  Line 7: listener set to this:

    JMSTest.<init> ()                  Line 8: sendToDestination not null:
      Sun Java System MQ Destination
      getName():        JMSSendToTestQueue
      Class:            com.sun.messaging.Queue
      getVERSION():     3.0
      isReadonly():     false
      getProperties():  
        imqDestinationName                  = JMSSendToTestQueue
        imqDestinationDescription           = A Description for the Destination Object}

    JMSTest.<init> ()                  Line : msgProducer not null:
        ConnectionID                        = 967799204788496640
        SessionID                           = 967799204788508160
        ProducerID                          = 967799204788513792
        DestName                            = JMSSendToTestQueue

    JMSTest.<init> ()                  Line 10: ObjectMessage created.
                                                Object is String: Hi There. I'm a Test Object.
Message Was Sent

1 个答案:

答案 0 :(得分:2)

您需要在连接上调用start(),以便MessageConsumer可以调度消息开始。您可以在不启动连接的情况下发送消息,但在启动之前无法接收任何消息。