您没有使用jmstemplate
,而是使用SimpleMessageListenerContainer
来接收消息。
如果您 是 使用模板,你将不得不使用的execute
方法有SessionCallback
,因为必须确认其内接收消息的会话的范围内。
但是,使用SimpleMessageListenerContainer
,您只需将设置sessionAckNowledgeMode
为Session.CLIENT_ACKNowLEDGE
。参见容器javadocs …
/**
* Message listener container that uses the plain JMS client API's
* {@code MessageConsumer.setMessageListener()} method to
* create concurrent MessageConsumers for the specified listeners.
*
* <p>This is the simplest form of a message listener container.
* It creates a fixed number of JMS Sessions to invoke the listener,
* not allowing for dynamic adaptation to runtime demands. Its main
* advantage is its low level of complexity and the minimum requirements
* on the JMS provider: Not even the ServerSessionPool facility is required.
*
* <p>See the {@link AbstractMessageListenerContainer} javadoc for details
* on ackNowledge modes and transaction options. Note that this container
* exposes standard JMS behavior for the default "AUTO_ACKNowLEDGE" mode:
* that is, automatic message ackNowledgment after listener execution,
* with no redelivery in case of a user exception thrown but potential
* redelivery in case of the JVM dying during listener execution.
*
* <p>For a different style of MessageListener handling, through looped
* {@code MessageConsumer.receive()} calls that also allow for
* transactional reception of messages (registering them with XA transactions),
* see {@link DefaultMessageListenerContainer}.
...
使用时jmstemplate
,您必须在会话范围内进行工作-这是…
首先,您必须在模板中启用客户端确认…
this.jmstemplate.setSessionAckNowledgeMode(Session.CLIENT_ACKNowLEDGE);
然后,将execute
方法与SessionCallback
…一起使用
Boolean result = this.jmstemplate.execute(session -> {
MessageConsumer consumer = session.createConsumer(
this.jmstemplate.getDestinationResolver().resolveDestinationName(session, "bar", false));
String result = null;
try {
Message received = consumer.receive(5000);
if (received != null) {
result = (String) this.jmstemplate.getMessageConverter().fromMessage(received);
// Do some stuff here.
received.ackNowledge();
return true;
}
}
catch (Exception e) {
return false;
}
finally {
consumer.close();
}
}, true);