Message Header Update Error in ActiveMQ during Retry - java

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.

Related

Pending Messages in ActiveMQ

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);
}
}
}

RabbitMQ listener can't convert message

I have message producer which sends message on rabbit using RabbitTemplate. It has message converter: Jackson2JsonMessageConverter.
I am trying to receive the message from the listener like that:
#RabbitListener(queues = "kolejka")
public void listen(String message) {
try {
log.info("Received ---------------------------------------------------");
log.info(message);
} catch (Exception e) {
log.debug("Error thrown while listening + " + e.getMessage());
}
}
Unfortunately, message is array of numbers from 45 to 130, it is like Ascii, so my listener has bad encoding.
I tried changing listener method to listen(Message message) and then
convert message to object like:
public void listen(Message messsage) {
Transfer transfer = (Transfer) jackson2JsonMessageConverter.fromMessage(messsage);
but it throws me warning that message wasn't encoded properly and was thrown on dead letter queue.

How to receive message from wildfly jms queue using consumer

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.

JMS MQ Implement retry logic without throwing exception

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

Java, activemq, Change settings of the message listener during the subscription

Is there a way to pass some variables other than the activemq message into the onMessage method during the subscription? Say if I have a gui which starts and stops this client and I want to change something in the message listener if I click a button in the gui. Is there anything I could do to achieve this?
public void onMessage(Message message) {
// TODO Auto-generated method stub
try {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
// how to swith between setting 1 and setting 2??
//setting 1
//save message to file
//setting 2
System.out.println("Received message" + textMessage.getText()
+ "'");
}
} catch (JMSException e) {
System.out.println("Caught:" + e);
e.printStackTrace();
}
}
Best regards,
The exact story is, I have a gui, and I want to change some settings
in the message listener when I click a button.
You need to pass that setting via some singleton/db/etc to the message handler.
In case if the message listener needs to write to a console you resend the message to the same queue/topic with the delayed property set as here https://activemq.apache.org/delay-and-schedule-message-delivery.html

Categories