问题描述
我正在将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)
。
在链接的示例中,初看起来没有预订,因为控制器方法返回Single<User>
,然后在这种情况下,预订者是REST操作调用者。