【问题标题】:Get mongodb documents with certain fields(projections) using Spring-Integration (annotations only)使用 Spring-Integration 获取具有某些字段(投影)的 mongodb 文档(仅限注释)
【发布时间】:2019-07-12 02:13:24
【问题描述】:

我正在尝试从 mongodb 集合中获取所有文档,这些文档在过去 5 分钟内仅使用某些字段(例如 field1、field2、field3 等)进行了修改。如何编写 LiteralExpression 来获取特定字段(投影)?

我当前的文字表达式返回包含所有字段的文档(_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】:

    事实上,expression 作为第二个MongoDbMessageSource 参数可以解析为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 包装器调用。在该代码中,您仍然需要构建这样的Query 对象才能委托给MongoTemplate.find()。这正是MongoDbMessageSource 中所做的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 2015-10-16
      • 2021-11-22
      • 2022-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多