正如 James Strachan 所说 - http://activemq.apache.org/ajax.html是解决您问题的理想开箱即用解决方案。
如果您仍想手动创建这样的解决方案,您可以在您的 Ajax servlet 中创建 JMS 连接(每个请求的连接)。出于这个原因考虑使用 Spring JMS 模板 ( http://static.springsource.org/spring/docs/2.5.x/reference/jms.html )。然后只需在 Servlet doGet/doPost 方法中接收消息。在这种情况下,请考虑接收的低超时值。这样的解决方案将适用于队列和持久主题。
For non-durable Topics consider external message listener. Spring MessageListenerContainer
is an excellent tool for that purpose:
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer
<property name="connectionFactory" ref="jmsFactory"/>
<property name="destination" ref="myTopic" />
<property name="messageListener" ref="lastTenUpdatesCache" />
</bean>
Bean lastTenUpdatesCache
will be a singleton bean implementing MesssageListener
. This bean would be responsible for caching last ten messages (just putting it into a java.util list). It will be injected into your Ajax servlet so in your doGet/doPost method you can ask it about last 10 messages sent to the topic.