何时何地是在TopicSubscriber上调用setMessageListener方法的最佳时机?

时间:2012-03-23 10:30:02

标签: java-ee jms jboss5.x hornetq

我正在尝试使用Topic订阅TopicSubscriber。致TopicSubscriber我正在尝试分配MessageListener。我在服务器启动时加载的Servlet的init()方法中添加了下面的代码:

String destName = "topic/userManagementTopic";
TopicConnectionFactory connectionFactory = null;
TopicConnection connection = null;
TopicSession session = null;
Topic topic = null;
InitialContext jndiContext = BlaBla.magicallyBuildTheCorrectInitialContext("userManagementTopic");
connectionFactory = (TopicConnectionFactory)jndiContext.lookup("java:/JmsXA");

topic = (javax.jms.Topic)jndiContext.lookup(destName);

connection = (TopicConnection)connectionFactory.createConnection("topicUser", "topicPwd");
session = (TopicSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
connection.start();
TopicSubscriber recv = session.createSubscriber(topic);
recv.setMessageListener(new UserManagementTopicListener());

问题是我从未超越最后一行,因为我得到了

javax.jms.IllegalStateException: This method is not applicable inside the application server. See the J2EE spec

我尝试应用我在互联网上找到的建议修补程序,将<config-property name="Strict" type="java.lang.Boolean">false</config-property>添加到我的jms-ds.xml中,但这不会修复它。

那么,我怎么能订阅主题并指出我想要的MessageListener

我正在使用jboss-5.1.0.GA而我的应用程序基于Struts。

感谢您阅读本文。

稍后编辑:我已通过使用"java:/ConnectionFactory"进行连接而超越了异常。现在它甚至更好,我没有错误,监听器不会处理消息。我只在向其添加MDB注释时收到消息,但我不想使用MDB。现在怎么办?

稍后编辑2: 我通过绑定侦听器使其工作如下:

String destName = "managementTopic";
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination dest = null;
MessageConsumer consumer = null;
ManagementTopicListener listener = null;
try {
    ref = BlaBla.magicallyBuildTheCorrectInitialContext(destName);

    jndiContext = ref.ctx;

    connectionFactory = connectionFactory = (ConnectionFactory)jndiContext.lookup("XAConnectionFactory");

    dest = (Topic)jndiContext.lookup("topic/" + destName);

    connection = connectionFactory.createConnection(ref.getPrinciple(), ref.getCredentials());
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    consumer = session.createConsumer(dest);

    listener = new ManagementTopicListener();
    consumer.setMessageListener(listener);

    connection.start();
    //very important to never close this connection for as long as you want to receive messages
} catch (Exception e) {
    System.out.println("kaboom " + e.getStackTrace());
    if (connection != null) {
        try {
            connection.close();
        } catch (JMSException ex) {
            System.out.println("exc " + ex.getLinkedException());
        }
    }
}

0 个答案:

没有答案