【发布时间】:2019-06-12 18:26:48
【问题描述】:
我在 web 上使用 apache camel 和 websphere mq 来发送和接收消息的例子不够多。我有一个示例代码,但我在代码中间感到震惊。任何人都可以帮助解决这个问题..
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Producer;
import org.apache.camel.util.IOHelper;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Client that uses the <a href="http://camel.apache.org/message-endpoint.html">Mesage Endpoint</a>
* pattern to easily exchange messages with the Server.
* <p/>
* Notice this very same API can use for all components in Camel, so if we were using TCP communication instead
* of JMS messaging we could just use <code>camel.getEndpoint("mina:tcp://someserver:port")</code>.
* <p/>
* Requires that the JMS broker is running, as well as CamelServer
*/
public final class CamelClientEndpoint {
private CamelClientEndpoint() {
//Helper class
}
// START SNIPPET: e1
public static void main(final String[] args) throws Exception {
System.out.println("Notice this client requires that the CamelServer is already running!");
AbstractApplicationContext context = new ClassPathXmlApplicationContext("camel-client.xml");
CamelContext camel = context.getBean("camel-client", CamelContext.class);
// get the endpoint from the camel context
Endpoint endpoint = camel.getEndpoint("jms:queue:numbers");
// create the exchange used for the communication
// we use the in out pattern for a synchronized exchange where we expect a response
Exchange exchange = endpoint.createExchange(ExchangePattern.InOut);
// set the input on the in body
// must be correct type to match the expected type of an Integer object
exchange.getIn().setBody(11);
// to send the exchange we need an producer to do it for us
Producer producer = endpoint.createProducer();
// start the producer so it can operate
producer.start();
// let the producer process the exchange where it does all the work in this oneline of code
System.out.println("Invoking the multiply with 11");
producer.process(exchange);
// get the response from the out body and cast it to an integer
int response = exchange.getOut().getBody(Integer.class);
System.out.println("... the result is: " + response);
// stopping the JMS producer has the side effect of the "ReplyTo Queue" being properly
// closed, making this client not to try any further reads for the replies from the server
producer.stop();
// we're done so let's properly close the application context
IOHelper.close(context);
}
}
我被这段代码打动了..
exchange.getIn()
我必须使用exchange.getOut() 发送消息吗?以及如何使用字符串构造消息并向其添加标头。
【问题讨论】:
-
到目前为止你做了什么?你被困在哪里了?
-
@ShellDragon 更新了问题,请查看编辑后的说明
-
exchange.getOut 从交换中获取 OUT 消息。如果用例合适,它可用于发送标头/正文。在解决 JMS 问题之前,您可能需要先熟悉一下骆驼。我添加了一些材料的链接来帮助你。
标签: spring apache-camel ibm-mq