gpt4 book ai didi

java - MessageListener 未监听 Oracle 队列中的消息

转载 作者:行者123 更新时间:2023-11-30 04:55:11 25 4
gpt4 key购买 nike

我已经实现了 Oracle Advanced Queue,并且正在编写一个监听器程序。以下是我的示例:

package com.myprog;

import java.io.File;
import java.io.FileInputStream;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.Session;
import javax.jms.TextMessage;

import oracle.jms.AQjmsFactory;
import oracle.jms.AQjmsSession;

import org.apache.log4j.Logger;

public class abc implements MessageListener, ExceptionListener {
private static String queueUserName = "admin";
private static String queueName = "my_queue";

// Initialize the logger
private static Logger log = Logger.getLogger(abc.class);

public static void main(String[] args) {
final String METHOD_NAME = "main()";

abc a = new abc();

Queue queue;
try {
QueueConnection QCon = getConnection();
Session session = QCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
QCon.start();

queue = ((AQjmsSession) session).getQueue(queueUserName, queueName);
MessageConsumer consumer = session.createConsumer(queue);

consumer.setMessageListener(a);
QCon.setExceptionListener(a);

consumer.close();
session.close();
QCon.close();
} catch (JMSException e) {
e.printStackTrace();
}

}

public static QueueConnection getConnection() {
String hostname = "myhost";
String oracle_sid = "mysid";
int portno = 1521;
String userName = "myapp";
String password = "pwd";
String driver = "thin";
QueueConnectionFactory QFac = null;
QueueConnection QCon = null;
try {
// get connection factory , not going through JNDI here
QFac = AQjmsFactory.getQueueConnectionFactory(hostname, oracle_sid, portno,driver);

// create connection
QCon = QFac.createQueueConnection(userName, password);
} catch (Exception e) {
e.printStackTrace();
}
return QCon;
}

@Override
public void onException(JMSException e) {
log.error(e);
}

@Override
public void onMessage(Message message) {
TextMessage msg = (TextMessage) message;

try {
String m = msg.getText();
System.out.println("m="+m);
log.info("MESSAGE RECEIVED " + m);
} catch (JMSException e) {
log.error(e);
}
}

}

请注意,该程序是一个独立程序,它将继续运行并监听 oracle 队列中的消息。

不幸的是,当我创建此类文件的 jar 并运行它时,它只是运行然后退出并仅消耗队列中的 1 条消息。为什么监听器不继续运行并监听队列?

我以为它会继续监听并检索队列中的所有消息,然后永远保持监听模式,但它的行为并非如此。

如果有人能告诉我出了什么问题,我将不胜感激。

谢谢

最佳答案

这都是因为您在启动后立即关闭连接/ session 。您需要该进程来启动一个在 JVM 中永久运行的守护线程。 JMS 不负责保持 JVM 运行。您需要创建一个刚刚 hibernate 的线程来完成此任务。

关于java - MessageListener 未监听 Oracle 队列中的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8775081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com