Created
May 23, 2018 11:25
-
-
Save bdarfler/784cdb61d4b9161c96fb364d9d1249a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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