Skip to content

Instantly share code, notes, and snippets.

@bdarfler
Created May 23, 2018 11:25
Show Gist options
  • Save bdarfler/784cdb61d4b9161c96fb364d9d1249a0 to your computer and use it in GitHub Desktop.
Save bdarfler/784cdb61d4b9161c96fb364d9d1249a0 to your computer and use it in GitHub Desktop.
@Component
public class Requestor {
private static final class ProducerConsumer implements SessionCallback<Message> {
private static final int TIMEOUT = 5000;
private final String msg;
private final DestinationResolver destinationResolver;
private final String queue;
public ProducerConsumer( final String msg, String queue, final DestinationResolver destinationResolver ) {
 this.msg = msg;
 this.queue = queue;
 this.destinationResolver = destinationResolver;
 }
public Message doInJms( final Session session ) throws JMSException {
 MessageConsumer consumer = null;
 MessageProducer producer = null;
 try {
 final String correlationId = UUID.randomUUID().toString();
 final Destination requestQueue =
 destinationResolver.resolveDestinationName( session, queue+".request", false );
 final Destination replyQueue =
 destinationResolver.resolveDestinationName( session, queue+".response", false );
 // Create the consumer first!
 consumer = session.createConsumer( replyQueue, "JMSCorrelationID = '" + correlationId + "'" );
 final TextMessage textMessage = session.createTextMessage( msg );
 textMessage.setJMSCorrelationID( correlationId );
 textMessage.setJMSReplyTo( replyQueue );
 // Send the request second!
 producer = session.createProducer( requestQueue );
 producer.send( requestQueue, textMessage );
 // Block on receiving the response with a timeout
 return consumer.receive( TIMEOUT );
 }
 finally {
 // Don't forget to close your resources
 JmsUtils.closeMessageConsumer( consumer );
 JmsUtils.closeMessageProducer( producer );
 }
 }
 }
private final JmsTemplate jmsTemplate;
@Autowired
 public Requestor( final JmsTemplate jmsTemplate ) {
 this.jmsTemplate = jmsTemplate;
 }
public String request( final String request, String queue ) {
 // Must pass true as the second param to start the connection
 return (String) jmsTemplate.execute( new ProducerConsumer( msg, queue, jmsTemplate.getDestinationResolver() ), true );
 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment