【发布时间】:2022-04-30 06:07:00
【问题描述】:
我想首先知道队列中已经存在多少条消息。以下类 Browser 将返回 Queue 中存在的消息数。现在,我希望用户输入要从队列中读取的消息数量,并仅向客户端显示该数量的消息。我不想读取队列中的所有消息,而只想读取用户想要读取的消息数。请检查代码并回复应该做什么。
public class Browser
{
public static void main(String[] args) throws Exception
{
| // get the initial context
| InitialContext ctx = new InitialContext();
|
| // lookup the queue object
| Queue queue = (Queue) ctx.lookup("queue/queue0");
|
| // lookup the queue connection factory
| QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
| lookup("queue/connectionFactory");
|
| // create a queue connection
| QueueConnection queueConn = connFactory.createQueueConnection();
|
| // create a queue session
| QueueSession queueSession = queueConn.createQueueSession(false,
| Session.AUTO_ACKNOWLEDGE);
|
| // create a queue browser
| QueueBrowser queueBrowser = queueSession.createBrowser(queue);
|
| // start the connection
| queueConn.start();
|
| // browse the messages
| Enumeration e = queueBrowser.getEnumeration();
| int numMsgs = 0;
|
| // count number of messages
| while (e.hasMoreElements()) {
| | Message message = (Message) e.nextElement();
| | numMsgs++;
| }
|
| System.out.println(queue + " has " + numMsgs + " messages");
|
| // close the queue connection
| queueConn.close();
}
}
To read the number of messages as per user's requirements....
String NUMBER = request.getParameter("number");
.......
.......
.......
connection.start();
for (int s = 0; s <= Integer.parseInt(NUMBER); s++){
while (true){
Message m = qReceiver.receive();
if (m != null){
if (m instanceof BytesMessage){
BytesMessage bytesMessage = (BytesMessage)m;
PrintStream buffer = null;
for ( int i = 0; i < (int)bytesMessage.getBodyLength(); i++) {
buffer.append((char) bytesMessage.readByte());
}
String msg = buffer.toString().trim();
System.out.println("Reading Message: " + msg);
}else if (m instanceof TextMessage){
TextMessage textMessage = (TextMessage)m;
System.out.println("Reading message: " + textMessage.getText());
}else {
break;
}
【问题讨论】:
-
这听起来就像循环一样简单,直到您阅读了 N 条消息,其中 N 是用户请求的数字。为什么这对您不起作用?您遇到了什么具体问题?
-
这种类型的功能更多地属于 JMS 代理的管理功能。查看队列中的#msgs 不是 JMS 规范的一部分。您使用的是哪个 JMS 提供程序?很多时候,这类事情有一个单独的管理 API。例如。 TIBCO EMS、ActiveMQ、IBM MQ 都有这种类型的管理 API。