【问题标题】:How to save an Object to Mongo db using reactive如何使用响应式将对象保存到 Mongo db
【发布时间】:2019-02-25 15:40:54
【问题描述】:

我有一个带有 spring-boot-starter-data-mongodb-reactive 依赖项的 springboot 项目。我有以下代码用于将学生对象保存在集合中:

@Autowired
private ReactiveMongoTemplate reactiveMongoTemplate;

public Mono<Student> save(String studentDetails) throws IOException {

Student student = mapper.readValue(studentDetails, Student.class);

Mono<Student> studentMono = reactiveMongoTemplate.save(student, "StudentCollection");

return studentMono;

} 

我已经配置了 mongo 客户端。仅当我阻止流时,上面的代码才会将数据保留在集合中。我该如何解决这个问题?

更新

我的 mongo 客户端有一个自定义配置,如下所示:

public class MongoConfig {

@Autowired
private MongoSslContext mongoSslContext;


@Bean
public MongoClient mongoClient() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException {

        mycustomSslContext = mongoSslContext.createSSLContext();


        SslSettings sslSettings = SslSettings.builder().context(mycustomSslContext).build();

        MongoClientSettings.builder().sslSettings(sslSettings);

        return MongoClients.create(new ConnectionString("mongodb://localhost:27019/studentDB?streamType=netty&ssl=true&authMechanism=MONGODB-X509"));       
}

public ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory() throws UnrecoverableKeyException,
        KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {        

    return new SimpleReactiveMongoDatabaseFactory(mongoClient(), "studentDB");

}

@Bean
public ReactiveMongoTemplate reactiveMongoTemplate() throws UnrecoverableKeyException, KeyManagementException,
        KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    return new ReactiveMongoTemplate(reactiveMongoDatabaseFactory());
}

}

【问题讨论】:

  • 您能否提供一个代码 sn-p 显示您打算如何/在何处使用此方法?这是一个 Spring WebFlux 应用程序吗?一个 Spring MVC 应用程序?还有什么?
  • 使用flatMap,看看我的回答会帮你解决
  • 上述方法在 StudentService 类中。该方法通过调用 studentService.save(payload) @BrianClozel 触发

标签: java mongodb spring-boot reactive-programming


【解决方案1】:

使用FlatMap,这就是你可以使用响应式的方式..

public Mono<Student> save(String studentDetails) throws IOException {

    Student student = mapper.readValue(studentDetails, Student.class);
    Mono<Student> studentMono = reactiveMongoTemplate.save(student);

    return studentMono;

} 

【讨论】:

  • 在这种情况下无法调用 flatMap,因为 student 不是流。我还需要将集合名称传递给 reactiveMongoTemplate。我没有使用存储库接口并直接使用 reactiveMongoTemplate,因为我需要进行较低级别的事务
  • 是简单的mongoClient还是你配置的??
  • 抱歉,刚刚检查了您的依赖项
  • 我刚刚使用了 Mono studentMono = reactiveMongoTemplate.save(student) 并且工作正常,我们需要通过 Collection 吗??。
  • 它具有自定义配置,是的,我需要传递集合名称以将对象保存到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多