【问题标题】:Reactive mongoDB in MicronautMicronaut 中的反应式 mongoDB
【发布时间】:2020-10-31 07:02:26
【问题描述】:

我正在使用带有 Micronaut 的 mongoDb 并尝试插入、获取、删除和更新记录。我已经遵循了这里的指导方针https://github.com/ilopmar/micronaut-mongo-reactive-sample

由于我没有在 MongoDB 中创建数据库,

Micronaut 配置

mongodb:
  uri: "mongodb://${MONGO_HOST:localhost}:${MONGO_PORT:27017/FeteBird-Product}"

存储库

@Singleton
public class Repository<T>  implements IRepository<T>{
    private final MongoClient mongoClient;
    public Repository(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    @Override
    public MongoCollection<T> getCollection(String collectionName, Class<T> typeParameterClass) {
        return mongoClient
                .getDatabase("FeteBird-Product")
                .getCollection(collectionName, typeParameterClass);
    }
}

插入操作

public Flowable<List<Product>> findByFreeText(String text) {
        LOG.info(String.format("Listener --> Listening value = %s", text));
        try {
            Product product = new Product();
            product.setDescription("This is the test description");
            product.setName("This is the test name");
            product.setPrice(100);
            product.setId(UUID.randomUUID().toString());
            Single.fromPublisher(this.repository.getCollection("product", Product.class).insertOne(product))
                    .map(item -> product);

        } catch (Exception ex) {
            System.out.println(ex);
        }

        return Flowable.just(List.of(new Product()));
    }

没有记录插入或创建数据库,我做错了什么?

【问题讨论】:

  • try 块中没有return

标签: java mongodb micronaut mongo-java micronaut-data


【解决方案1】:

是的,没有创建任何内容,因为您使用的是响应式Single 而没有订阅。然后它永远不会被执行。所以,你必须打电话给subscribe() 告诉Single 它可以开始工作了:

Single.fromPublisher(repository.getCollection("product", Product.class).insertOne(product))
    .subscribe();

注意:当您不使用订阅结果时,项目到产品.map(item -&gt; product)的映射是不必要的。


第一次查看链接示例中没有订阅,因为控制器方法返回Single&lt;User&gt;,然后在这种情况下订阅者是 REST 操作调用者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 2019-05-23
    相关资源
    最近更新 更多