【发布时间】:2012-02-05 03:35:40
【问题描述】:
异步 JMS 如何工作?我有下面的示例代码:
public class JmsAdapter implements MessageListener, ExceptionListener
{
private ConnectionFactory connFactory = null;
private Connection conn = null;
private Session session = null;
public void receiveMessages()
{
try
{
this.session = this.conn.createSession(true, Session.SESSION_TRANSACTED);
this.conn.setExceptionListener(this);
Destination destination = this.session.createQueue("SOME_QUEUE_NAME");
this.consumer = this.session.createConsumer(destination);
this.consumer.setMessageListener(this);
this.conn.start();
}
catch (JMSException e)
{
//Handle JMS Exceptions Here
}
}
@Override
public void onMessage(Message message)
{
try
{
//Do Message Processing Here
//Message sucessfully processed... Go ahead and commit the transaction.
this.session.commit();
}
catch(SomeApplicationException e)
{
//Message processing failed.
//Do whatever you need to do here for the exception.
//NOTE: You may need to check the redelivery count of this message first
//and just commit it after it fails a predefined number of times (Make sure you
//store it somewhere if you don't want to lose it). This way you're process isn't
//handling the same failed message over and over again.
this.session.rollback()
}
}
}
但我是 Java 和 JMS 的新手。我可能会在 onMessage 方法中使用消息。但我不知道它是如何工作的。
我需要在 JmsAdapter 类中添加 main 方法吗?添加 main 方法后,是否需要创建一个 jar,然后以“java -jar abc.jar”的形式运行该 jar?
非常感谢任何帮助。
更新:我想知道的是,如果我添加 main 方法,我应该简单地在 main 中调用 receiveMessages() 吗?然后在运行之后,监听器会继续运行吗?如果有消息,会在onMessage方法中自动检索吗?
另外,如果监听器一直在监听,它不会占用 CPU 吗???在线程的情况下,当我们创建一个线程并将其置于睡眠状态时,CPU 利用率为零,如果是侦听器,它是如何工作的?
注意:我只有 Tomcat 服务器,我不会使用任何 jms 服务器。我不确定监听器是否需要任何特定的 jms 服务器,例如 JBoss?但无论如何,请假设我除了 tomcat 什么都没有。 谢谢!
【问题讨论】:
-
我不确定您的问题与 JMS 有什么关系。您似乎在问“如何在 Java 中运行程序”。
-
您无需创建 main 方法,一旦部署在服务器上,onMessage() 方法就会处理发送到您的班级正在观看的队列的任何消息。 onMessage() 将包含您想要在消息到达队列时执行的逻辑。
-
你用什么来实现 JMS?
-
@Logan,所以,我的 JMSAdapter 类不会有任何 main 方法,对吧?所以,我应该把这个类打包在一个 jar 中,然后使用“java -jar JMSAdapter &”来部署它,对吧?编译器将如何调用 receiveMessages() 方法?
-
@Dave,我已经设置了 Oracle 队列并且我们有一些工作正在这个队列中创建消息。我只想写一个程序,它会不断地监听消息并在它们可用时立即处理它们,