EJB3 - Send a JMS Message from a Stateless EJB

From Shrubbery

Jump to: navigation, search


Sending a JMS message from a Stateless Session EJB

Thus example sends a single ObjectMessage. It is non-transactional (i.e. the message gets sent right away, it doesn't wait for the method to exit), and it does not wait for acknowledgement from the receiver.

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class SenderBean
{
    @Resource(mappedName= "java:/JmsXA")
    private ConnectionFactory connectionFactory;

    @Resource(mappedName="queue/myQueue")
    private Queue asyncQueue;

    public void sendObjectMessage(Serializable serializable)
    {
        if (serializable == null)
            throw new IllegalArgumentException("object cannot be null!");
        QueueConnection con = null;
        QueueSession ses = null;
        QueueSender sender = null;
        try
        {
            QueueConnectionFactory qcf = (QueueConnectionFactory) connectionFactory;
            con = qcf.createQueueConnection();
            ses = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            sender = ses.createSender(asyncQueue);
            ObjectMessage msg = ses.createObjectMessage(serializable);
            sender.send(msg);
        }
        catch (JMSException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            JmsHelper.close(sender,ses,con);
        }
    }
}

See:

Personal tools