首页 > 解决方案 > 访问 Camel EIP bean 中消息体的元素

问题描述

我有一个使用 Content Enricher EIP 的骆驼路线。所以我的路线是这样的:

AggregationStrategy aggregationStrategy = new TestAggregationStrategy(); 

from("timer:myTimer?repeatCount=1")
.setBody(simple("{\"channel\": \"orderbook\", \"market\": \"BTC/USD\", \"type\": \"update\", \"data\": {\"time\": 1626139758.986094, \"checksum\": 195176195, \"bids\": [[32965.0, 0.0], [32962.0, 3.4015]], \"asks\": [], \"action\": \"update\"}}"))
.setHeader(MongoDbConstants.CRITERIA, constant(Filters.eq("market", "BTC/USD")))
.enrich("mongodb:mongo?database=dev&collection=order&operation=findOneByQuery", aggregationStrategy)
.log("Test: ${body}");

在 TestAggregationStrategy 我有两个交换,原始的和资源的。

public class TestAggregationStrategy implements AggregationStrategy {
    public Exchange aggregate(Exchange original, Exchange resource) {
        System.out.println("Original: " + original.getMessage().getBody().toString());
        
    
        String bidsJsonQuery = "$.data.bids";
        DocumentContext updateContext = JsonPath.parse(original.getMessage().getBody().toString());
        List<String> updateJsonString = updateContext.read(bidsJsonQuery);
        
        System.out.println(resource.getMessage().getBody());
        
        //ArrayList test = (ArrayList) resource.getMessage().getBody(List.class);
        Object test = resource.getMessage().getBody();
        System.out.println("Test: " + test);

        
        System.out.println("Resource: " + resource.getMessage().getBody()); 
        return resource; 
    }
}

我可以使用resource.getMessage().getBody() 获取消息内容,它返回某种对象。如果我将它放入 println() 中,它会打印 Mongo 文档。当我使用调试器检查资源交换时,它看起来像这样:

交换 > 在 > 正文(“文档”)

其中包含一个哈希映射数组。在此示例中,其中一个哈希映射的键为“bids”,其值为数组列表。

您可以直接访问这些值吗?数组列表?我一直在试验,但我无法通过 getBody()。

在此处输入图像描述

标签: mongodbspring-bootapache-camel

解决方案


您的代码(Jsonpath 查询和转换)没问题,但“出价”不是List<String>

在您设置的消息正文中,“出价”是一个List<List<Double>>.

当我获取您的 Json 字符串时,我可以像这样在纯 Java 中提取“出价”

    String jsonString = "{\"channel\": \"orderbook\", \"market\": \"BTC/USD\", \"type\": \"update\", \"data\": {\"time\": 1626139758.986094, \"checksum\": 195176195, \"bids\": [[32965.0, 0.0], [32962.0, 3.4015]], \"asks\": [], \"action\": \"update\"}}";
    String bidsJsonQuery = "$.data.bids";
    DocumentContext updateContext = JsonPath.parse(jsonString);
    List<List<Double>> bids = updateContext.read(bidsJsonQuery);
    for (List<Double> bid : bids) {
        for (Double singleBid : bid) {
            logger.info("{}", singleBid);
        }
    }

记录器的输出是

32965.0
0.0    
32962.0
3.4015 

顺便说一句:在您的代码中,您解析original消息正文。在你写的关于resource身体的文本中。这是您的代码中的错误吗?


推荐阅读