In terms of JMS performance, I have read that ObjectMessage should be avoided for performance reasons.
How bad are ObjectMessage performance-wise? Should I serialize to a BytesMessage and manually deserialize?
The performance overhead of ObjectMessage is because of the java.io serialization process. If you do that yourself and use ByteMessage, you're just doing what JMS would do itself, and you'll be no better off.
If you need to send java objects via JMS, you should use ObjectMessage, that's what the API provides. This allows the container to make some optimizations, e.g. JBoss will use its own proprietary serialization protocol, which is considerably faster than the standard java.io one.
Example using Jackson Smile data format which can be up to 50% faster AND smaller than JDK serialization, so BytesMessage in this case will beat ObjectMessage:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.fasterxml.jackson.dataformat.smile.SmileGenerator;
import org.springframework.jms.core.MessageCreator;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
public class BytesMessageCreator<T> implements MessageCreator
{
public static final ObjectMapper
MAPPER=new ObjectMapper(new SmileFactory().disable(SmileGenerator.Feature.ENCODE_BINARY_AS_7BIT));
final String messageId;
final T pojo;
public BytesMessageCreator(final T pojo)
{
messageId=null;
this.pojo=pojo;
}
public BytesMessageCreator(final String messageId, final T pojo)
{
this.messageId=messageId;
this.pojo=pojo;
}
@Override
public Message createMessage(final Session session) throws JMSException
{
try{
final BytesMessage message=session.createBytesMessage();
message.writeBytes(MAPPER.writeValueAsBytes(pojo));
if(messageId != null){
message.setJMSMessageID(messageId);
}
return message;
} catch(Exception e){
throw new RuntimeException(e);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With