Micronaut 中的反应式 mongoDB

Reactive mongoDB in Micronaut

我正在将 mongoDb 与 Micronaut 一起使用,并尝试插入、获取、删除和更新记录。我遵循了这里的指南 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()));
    }

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

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

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

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


乍一看,链接示例中没有订阅,因为控制器方法 returns Single<User> 然后订阅者在这种情况下是 REST 操作调用者。