[英]What messaging pattern should I use to process and return responses from a rest request?
我有一个与此类似的中心和辐射架构:
GET请求进入集线器并将其路由到其中一个辐条进行处理。 在集线器上,我还将请求放在带有UUID的映射中,以便在从处理中获取数据时可以返回正确的响应。 辐条是相同的,用于平衡负载。 然后我需要将信息从辐条传递回集线器并返回适当的响应。
我想使用JMS进行消息传递。
实现此目的的集成模式的最佳组合是什么?
您已经在Vert.x中拥有请求/回复,因此您可以使用大约20行代码实现此行为:
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
Router router = Router.router(vertx);
router.get("/").handler((request) -> {
// When hub receives request, it dispatches it to one of the Spokes
String requestUUID = UUID.randomUUID().toString();
vertx.eventBus().send("processMessage", requestUUID, (spokeResponse) -> {
if (spokeResponse.succeeded()) {
request.response().end("Request " + requestUUID + ":" + spokeResponse.result().body().toString());
}
// Handle errors
});
});
// We create two Spokes
vertx.deployVerticle(new SpokeVerticle());
vertx.deployVerticle(new SpokeVerticle());
// This is your Hub
vertx.createHttpServer().requestHandler(router::accept).listen(8888);
}
这就是Spoke的样子:
/**
* Static only for the sake of example
*/
static class SpokeVerticle extends AbstractVerticle {
private String id;
@Override
public void start() {
this.id = UUID.randomUUID().toString();
vertx.eventBus().consumer("processMessage", (request) -> {
// Do something smart
// Reply
request.reply("I'm Spoke " + id + " and my reply is 42");
});
}
}
尝试在浏览器中访问http:// localhost:8888 /
您应该会看到每次都会生成请求ID,而只有两个Spoke中的一个响应您的请求。
好吧,如果我理解你的设计正确,这似乎是请求/回复场景,因为辐条实际上是返回一些响应。 如果没有,则会发布/订阅。
您可以将ActiveMQ用于jms并请求/回复。 见这里: http : //activemq.apache.org/how-should-i-implement-request-response-with-jms.html
至于细节,这一切都取决于您的要求,响应是否会立即发送,还是长期运行?
如果它是一个长时间运行的过程,您可以避免请求/回复并使用火灾和遗忘方案。
基本上,集线器在队列上触发消息,该队列正由一个分支组件监听。 完成后端处理后,它会将响应返回给集线器监控的队列。 您可以通过某个correlationId关联请求/响应。 在请求部分期间,您可以将correlationId保存在缓存中以与响应匹配。 在请求/回复方案中,这是由基础结构为您完成的,但不用于长时间运行的进程。
总结一下:使用ActiveMQ进行JMS的消息处理。 使用Camel作为REST位。 如果您确定您希望响应相当快,请使用请求/回复。 如果您希望响应花费很长时间但必须匹配消息correlationIds,请使用fire并忘记。
如果您希望将Camel与JMS一起使用,那么您应该使用Request-Reply EIP ,并且就示例而言,您可以通过Camel的官方示例提供相当好的一个 - 它可能有点旧但它仍然非常有效。
虽然您可以通过Spring忽略示例的Camel配置,但其路由定义提供了足够的信息:
public class SpokeRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("jms:queue:spoke")
.process(e -> {
Object result = ...; // do some processing
e.getIn().setBody(result); // publish the result
// Camel will automatically reply if it finds a ReplyTo and CorrelationId headers
});
}
}
然后所有HUB需要做的是调用:
ProducerTemplate camelTemplate = camelContext.createProducerTemplate();
Object response = camelTemplate.sendBody("jms:queue:spoke", ExchangePattern.InOut, input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.