I have deployed my Java-MDB based application using ActiveMQ as messaging service . I could see that a few messages have been in pending status for quite some time on some queues. I have read that this happens when ActiveMQ delivers the message and consumer consumes the message but doesn't send the ack back. But I could not see any related loggers on the consumer/application side which proves that the message is consumed.
Could anyone please help me understand the reason of message being stuck in pending state.
Edit - Adding the details:
We are using Auto-acknowledge as acknowledgeMode and below is the onMessage method used on consumer side.
public void onMessage(Message message) {
try {
// Clear all ThreadLocal in SQLQueryHelper.
SQLQueryHelper.clearCache();
String messageOut = processMessage(message);
// if there is a reply, send it out
if (messageOut != null) {
logger.warn(LoggerKeys.LOG_1_ARGS,
new String[] {"Reply from MDB not supported. " + messageOut});
}
} catch (Throwable e) {
logger.error(LoggerKeys.LOG_1_ARGS,
new String[] {"Error encountered: " + e.toString()});
try {
//put message on error queue
handleError(message, e);
} catch (Throwable e2) {
//retry to put message on error queue
handleErrorAndRollBack(message, e2);
}
}
}
Related
I encountered a knotty problem when receiving message from WildFly JMS queue. My code is below:
Session produceSession = connectionFactory.createConnection().createSession(false, Session
.CLIENT_ACKNOWLEDGE);
Session consumerSession = connectionFactory.createConnection().createSession(false, Session
.CLIENT_ACKNOWLEDGE);
ApsSchedule apsSchedule = new ApsSchedule();
boolean success;
MessageProducer messageProducer = produceSession.createProducer(outQueueMaxusOrder);
success = apsSchedule.sendD90Order(produceSession,messageProducer, d90OrderAps);
if (!success) {
logger.error("Can't send APS schedule msg ");
} else {
MessageConsumer consumer = consumerSession.createConsumer(inQueueDeliveryDate);
data = apsSchedule.receiveD90Result(consumerSession,consumer);
}
then getting into the receiveD90Result():
public DeliveryData receiveD90Result(Session session, MessageConsumer consumer) {
DeliveryData data = null;
try {
Message message = consumer.receive(10000);
if (message == null) {
return null;
}
TextMessage msg = (TextMessage) message;
String text = msg.getText();
logger.debug("Receive APS d90 result: {}", text);
ObjectMapper mapper = new ObjectMapper();
data = mapper.readValue(text, DeliveryData.class);
} catch (JMSException je) {
logger.error("Can't receive APS d90 order result: {}", je.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
consumer.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
return data;
}
But when implementing the consumer.receive(10000), the project can't get a message from queue. If I use asynchronous way of MDB to listen the queue, I can get the message from queue. How to resolve it?
There are multiple modes you can choose to get a message from the queue. Message Queues are by default asynchronous in usage. There are however cases when you want to read it synchronously , for example sending a message with account number and using another queue to read the response and match it with a message id or a message correlation id. When you do a receive , the program is waiting for a message to arrive within that polling interval specified in receive.
The code snippet you have , as i see it uses the psuedo synchronous approach. If you have to use it as an MDB , you will have to implement message driven bean (EJB Resource) or message listener.
The way that MDB/Message Listener works is more event based , instead of a poll with a timeout (like the receive) , you implement a callback called onMessage() that is invoked every time there is a message. Instead of a synchronous call , this becomes asynchronous. Your application may require some changes both in terms of design.
I don't see where you're calling javax.jms.Connection.start(). In fact, it doesn't look like you even have a reference to the javax.jms.Connection instance used for your javax.jms.MessageConsumer. If you don't have a reference to the javax.jms.Connection then you can't invoke start() and you can't invoke close() when you're done so you'll be leaking connections.
Furthermore, connections are "heavy" objects and are meant to be re-used. You should create a single connection for both the producer and consumer. Also, if your application is not going to use the javax.jms.Session from multiple threads then you don't need multiple sessions either.
I have two applications within my server, and use JMS via ActiveMQ to send messages between the two. My two apps are as follows
Web service - accepts HTTP requests, validates, then sends messages to be executed by the other application.
Exec App - accepts object messages, executes order, sends execution report back to the web service to present to the client.
My Exec app receives messages from the Web service within 200ms, no problems there. However when I send an exec report, the message can hang in the queue for over 10 seconds before being received by the web service. I am using the same code for both side's consumers so I am unsure what the cause would be.
Here is my message producer in the Exec App -
public void createAndSendExecReport(OrderExecutionReport theReport){
try {
logger.debug("Posting exec report: " +theReport.getOrderId());
this.excChannelMessageProducer.send(createMessage(theReport));
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
[there is a createMessage method which converts my POJO into an object message]
MessageListener listener = new MessageListener() {
#Override
public void onMessage(Message message) {
logger.debug("Incoming execution report");
try {
OrderExecutionReport report = (OrderExecutionReport)((ObjectMessage)message).getObject();
consumeExecutionReport(report);
} catch (Exception e) {
logger.error("Message handling failed. Caught: " + e);
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.error(sw.toString());
}
}
};
I get the log message "sending execution report"
Then nothing in the web service for up to 15 seconds later until finally I get "incoming ... "
What could be the cause of this?
Make sure you have enough MDBs running on the Exec App so they can handle the load.
I have a requirement where I have to add and update message header in case of message retry.
Here is my listener or consumer. My message is getting retried but I am getting Exception when setting the header. Please advise the correct way of doing this.
As per JMS spec and it says that Message Headers are never read-only.
javax.jms.MessageNotWriteableException: Message properties are read-only
public void onMessage(Message message) {
if (message != null && message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
String input = textMessage.getText();
throw new Exception();
} catch (Throwable t) {
t.printStackTrace();
try {
message.setStringProperty("retryable","YES");
} catch (JMSException e) {
e.printStackTrace();
}
throw new RuntimeException(t);
}
}
}
What you are trying won't work for a number of reasons. You are attempting to set a message PROPERTY on an incoming message which will indeed be read-only. The message you receive is a copy of the actual message and not the one that would be resent if inside a TX and was eligible for redelivery.
To do any sort of update to a delivered message that encounters an error during its processing you need to create a new instance and decorate it with the appropriate information and then place it back on the Destination using a MessageProducer.
I have a JMSReceiver class which is listening on a MQ Queue. This class implements the MessageListener interface. I wish to implement the logic to retry a message for specified number of times by getting the message to rollback. To do so I have to catch the business exception and wrap it in a RuntimeException so that message gets rolled back to the MQ and gets replayed. i wish to implement this in better way.
Current Implementation
class JMSReceiver implements MessageListener{
public void onMessage(Message msg){
logger.info("**********Message received in consumer");
try {
//Do some business which throws a business exception
} catch (Exception e) {
try {
logger.info("####Redelivery count"+msg.getIntProperty("JMSXDeliveryCount"));
if(msg.getIntProperty("JMSXDeliveryCount")<10){
logger.info("####MQ ISSUE: Redelivery attempted for message. Redelivery attempt: "+msg.getIntProperty("JMSXDeliveryCount"));
throw new RuntimeException("Redelivery Attempted"+e.getMessage());
}else{
logger.info("####MQ ISSUE: Redelivery attempts exhausted for message");
}
} catch (JMSException e1) {
e1.printStackTrace();
logger.info("####MQ ISSUE: Exception occured while getting JMSXDeliveryCount");
}
}
}
Expected
The above implementation works. It rollsback the message to MQ and the redelivery count increases. I even tried doing session.rollback() but when I do that the redelivery count does not increase and I can replay the message. Please advise a better way to implement this ?
You can create JMS session with CLIENT_ACKNOWLEDGE as message acknowledge mode. And then in the onMessage() method, do not call msg.Acknowledge(). Not calling msg.Acknowledge() will ensure the same is delivered again.
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Note that calling Acknowledge() on one message will acknowledge all messages received since the last time the method was called.
Update
Session creation
connection = cf.createConnection("user","password");
System.out.println("Connection created.");
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
System.out.println("Session created.");
OnMessage() method - Message is being acknowledged on 6th attempt.
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
try {
// Display the message that just arrived
System.out.println(msg);
if(msg.getIntProperty("JMSXDeliveryCount") > 5){
msg.acknowledge();
}
} // end try
catch (Exception e) {
System.out.println("Exception caught in onMessage():\n" + e);
}
return;
} // end onMessage()
}); // end setMessageListener
I want to send a message to all active clients.
#OnMessage
public void onMessage(String message, Session session) {
switch (message) {
case "latencyEqualize":
for (Session otherSession : session.getOpenSessions()) {
RemoteEndpoint.Basic other = otherSession.getBasicRemote();
String data = "Max latency = "
+ LatencyEqualizer.getMaxLatency(latencies);
try {
other.sendText(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
break;
default:
RemoteEndpoint.Basic other = session.getBasicRemote();
try {
other.sendText(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Something is wrong with this code. When i send message "latencyEqualize" from the first client the server answers only to the same client. Other clients don't receive message "Max latency = 15". But when the second client sends to server any message, he recieves back "Max latency = 15". And all future calls to server return the message from previous call.
Is there a way to avoid this. I want all clients get "Max latency" message when one of them send "latencyEqualize" message to the server.
The reason why only one client receives your message is that session variable contains connection only of that client who sent you message.
To send your message to all clients, store their connections in some collection (for example, ArrayList<Session>) in onOpen() method, and then iterate though that collection to get connections of all of your clients