title: How to setup RabbitMQ RPC in a web context
body: <h2>RabbitMQ RPC</h2>
  
  <p>I decided to use RabbitMQ RPC as described <a href="http://www.rabbitmq.com/tutorials/tutorial-six-java.html" rel="nofollow">here</a>.</p>
  
  <h2>My Setup</h2>
  
  <p>Incoming web requests (on Tomcat) will dispatch RPC requests over RabbitMQ to different services and assemble the results. I use one reply queue with one custom consumer that listens to all RPC responses and collects them with their correlation id in a simple hash map. Nothing fancy there.
  This works great in a simple integration test on controller level.</p>
  
  <h2>Problem</h2>
  
  <p>When I try to do this in a web project deployed on Tomcat, Tomcat refuses to shut down. jstack and some debugging learned me a thread is spawn to listen for the RPC response and is blocking Tomcat from shutting down gracefully. I guess this is because the created thread is created on application level instead of request level and is not managed by Tomcat. When I set breakpoints in <code>Servlet.destroy()</code> or <code>ServletContextListener.contextDestroyed(ServletContextEvent sce)</code>, they are not reached, so I see no way to manually clean things up.</p>
  
  <h2>Alternative</h2>
  
  <p>As an alternative, I could use a new reply queue (and simple QueueingConsumer) for each web request. I've tested this, it works and Tomcat shuts down as it should. But I'm wondering if this is the way to go.. Can a RabbitMQ cluster deal with thousands (or even millions) of short living queues/consumers? I can imagine queues aren't that big, but still.. constantly broadcasting to all cluster nodes.. the total memory footprint..</p>
  
  <h2>Question</h2>
  
  <p>So in short, is it wise do create a queue for each incoming web request or how should I setup RabbitMQ with one queue and consumer so Tomcat can shutdown gracefully?</p>