簡體   English   中英

使用Spring-Integration獲取具有某些字段(投影)的mongodb文檔(僅限注釋)

[英]Get mongodb documents with certain fields(projections) using Spring-Integration (annotations only)

我試圖從mongodb集合中獲取所有文檔,這些文檔在最后5分鍾內僅使用某些字段進行了修改(比如field1,field2,field3等)。 如何編寫LiteralExpression以獲取特定字段(投影)?

我當前的Literal Expression返回包含所有字段的文檔(_id是我的集合中文檔創建的時間戳):

public String getLiteralExpression(){
        long innerBoundary = Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli();
        long outerBoundary = Instant.now().toEpochMilli();
        String expression = new StringBuilder()
                .append("{'_id': {'$gt': ")
                .append(innerBoundary)
                .append(", '$lt' : ")
                .append(outerBoundary)
                .append("}}")
                .toString();
        return expression;
    }
}

在InboundChannelAdapter中調用的是

@Bean
@InboundChannelAdapter(value = "pubSubChannel", poller = @Poller(fixedRate = "30000"))
public MessageSource<Object> DbReadingMessageSource() {

    Expression expression = new SpelExpressionParser().parseExpression("@myBean.getLiteralExpression()");

    MongoDbMessageSource messageSource = new MongoDbMessageSource(mongoTemplate, expression);
    messageSource.setCollectionNameExpression(new LiteralExpression(mongoTemplate.getCollectionName(MyEntity.class)));
    IntegrationFlows.from(messageSource);
    return messageSource;
}

有沒有辦法我只能使用MongoTemplate或MongoDbFactory而不是LiteralExpression來獲取MongoDbMessageSource形式的某些字段(投影)或任何其他可以提供給我的pubsubChannel管道的格式。

事實上,作為第二個MongoDbMessageSource參數的expression可以解析為org.springframework.data.mongodb.core.query.Query對象。 所以,它可能不僅僅是一個簡單的文字表達 對於您的投影用例,您可以編寫如下內容:

new BasicQuery([QUERY_STRING], [FIELD_STRING])

@myBean.getLiteralExpression()返回。

Query API非常靈活,並為最終的MongoDB查詢提供了許多流暢的鈎子。 例如,它有一個fields()用於include/exclude您想要返回的特定字段的回調。

有關Spring Data MongoDB手冊中Query API的更多信息: https//docs.spring.io/spring-data/mongodb/docs/2.1.5.RELEASE/reference/html/#mongodb-template-query

如果您想直接使用MongoTemplate ,則需要編寫一個自定義代碼,該代碼應該從具有相同@InboundChannelAdapter配置的MethodInvokingMessageSource包裝器中@InboundChannelAdapter 在該代碼中,您仍然需要構建這樣的Query對象以便能夠委托給MongoTemplate.find() 這正是MongoDbMessageSource所做的。

毫無疑問:你的DbReadingMessageSource()配置有點錯誤。 你不能調用IntegrationFlows.from(messageSource); 從那個bean定義。 必須將MongoDbMessageSource配置為單獨的@Bean並且沒有@InboundChannelAdapter注釋。 IntegrationFlow必須是另一個@Bean ,你真的可以使用from() DbReadingMessageSource() from() 但同樣:沒有@InboundChannelAdapter 請參見參考手冊: https//docs.spring.io/spring-integration/docs/current/reference/html/#java-dsl-inbound-adapters

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM