使用Spring-Integration获取具有某些字段(投影)的mongodb文档(仅限注释)

问题描述 投票:3回答:1

我试图从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管道的格式。

java spring-boot spring-data spring-integration spring-data-mongodb
1个回答
1
投票

这是一个事实,expression作为第二个MongoDbMessageSource论证可以解析为org.springframework.data.mongodb.core.query.Query对象。所以,它可能不仅仅是一个简单的文字表达。对于您的投影用例,您可以编写如下内容:

new BasicQuery([QUERY_STRING], [FIELD_STRING])

从你的@myBean.getLiteralExpression()返回。

Query API非常灵活,并为最终的MongoDB查询提供了许多流畅的钩子。例如,对于您希望返回的特定字段,它有fields()用于include/exclude回调。

有关Query API的更多信息,请参阅Spring Data MongoDB手册:https://docs.spring.io/spring-data/mongodb/docs/2.1.5.RELEASE/reference/html/#mongodb-template-query

如果你想直接使用MongoTemplate,你需要编写一个自定义代码,应该从MethodInvokingMessageSource包装器调用相同的@InboundChannelAdapter配置。在该代码中,您仍然需要构建这样一个Query对象,以便能够委托给MongoTemplate.find()。这正是MongoDbMessageSource所做的。

毫无疑问:你的DbReadingMessageSource()配置有点错误。你不能从那个bean定义中调用IntegrationFlows.from(messageSource);MongoDbMessageSource必须配置为单独的@Bean并且已经没有@InboundChannelAdapter注释。 IntegrationFlow必须是另一个@Bean,你真的可以使用你DbReadingMessageSource()from()。但同样:没有@InboundChannelAdapter。参见参考手册:https://docs.spring.io/spring-integration/docs/current/reference/html/#java-dsl-inbound-adapters

© www.soinside.com 2019 - 2024. All rights reserved.