異步JMS如何工作?我有下面的示例代碼:JMS如何在Java中工作?
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類中添加主要方法?添加主要方法後,我需要創建一個罐子&然後運行jar爲「java -jar abc.jar」?
任何幫助,非常感謝。
更新:我想知道的是,如果我添加主要方法,我應該簡單地調用receiveMessages()在主?然後運行後,聽衆會繼續運行嗎?如果有消息,它會自動檢索onMessage方法嗎?
此外,如果聽者不斷地收聽,是不是需要CPU?在線程的情況下,當我們創建一個線程&將其置於睡眠狀態時,CPU利用率爲零,如果聽者情況下它如何工作?
注意:我只有Tomcat服務器&我不會使用任何jms服務器。我不確定偵聽器是否需要任何特定的jms服務器,如JBoss?但無論如何,請假設我除了tomcat之外沒有任何東西。 謝謝!
我不知道你的問題與JMS做什麼。您似乎在問「如何在Java中運行程序」。 – skaffman 2012-01-08 00:04:16
一旦部署在服務器上,您不會創建主要方法,onMessage()方法會處理髮送到您的班級正在觀察的隊列的所有消息。 onMessage()將包含消息到達隊列時要執行的邏輯。 – Logan 2012-01-08 00:36:55
你用什麼JMS實現? – 2012-01-08 00:40:17