如何使用Apache Camel和MongoDB创建动态等于查询?
我想从Apache Camel路由动态查询MongoDB集合。Apache Camel docs show how to query a collection using a constant
value:
from("direct:findOneByQuery")
.setHeader(MongoDbConstants.CRITERIA, Filters.eq("name", "Raul Kripalani"))
.to("mongodb:myDb?database=flights&collection=tickets&operation=findOneByQuery")
.to("mock:resultFindOneByQuery");
虽然我确信这对某些人很有用,但我试图查询具有动态生成值的集合,例如使用Exchange头。您是如何做到这一点的?
解决方案
对于初学者而言,上述语句无法编译。在另一个问题中向我指出,当前的Apache Camel MongoDB文档中有一个错误,上面的setHeader
行应该是:
.setHeader(MongoDbConstants.CRITERIA, constant(Filters.eq("name", "Raul Kripalani"))
我最终完成此操作的方式是通过创建一个anonomyousExpression
:
import com.mongodb.client.model.Filters;
import com.mongodb.BasicDBObject;
import org.bson.conversions.Bson;
@Component
public class NotifyClientRoute extends RouteBuilder {
public static final String NOTIFY_CLIENT_URI = "direct:notifyClient";
@Override
public void configure() throws Exception {
from(NOTIFY_CLIENT_URI)
.log("Determining which client gets the deletion request next for DR request '${header.drRequestId}'.")
.setHeader(MongoDbConstants.CRITERIA, new Expression() {
@Override
public <T> T evaluate(Exchange exchange, Class<T> type) {
String drRequestId = exchange.getIn().getHeader("drRequestId", String.class);
Bson equalsClause = Filters.eq("drRequestId", drRequestId);
// Alternatively:
// Bson equalsClause = new BasicDBObject("drRequestId", new BasicDBObject("$eq", drRequestId));
return exchange.getContext().getTypeConverter().convertTo(type, equalsClause);
};
})
.to("mongodb:mongoClient?database=mydb&collection=mycollection&operation=findOneByQuery")
.log("Query returned: '${body}'");
}
}
附加说明:我没有在[2-1]>中提出返回语句。我遇到了类型错误,所以我查看了Camel库中包含的另一个Apache CamelExpression
实现返回的内容,我找到了那个RETURN子句。
相关文章