如何使用 WebFlux 和 ReactiveMongoRepository 保存元素?
How to save an element with WebFlux and ReactiveMongoRepository?
我想写第一个程序webFlux
和ReactiveMongoRepository
。
我有存储库:
@Repository
public interface personRepository extends ReactiveMongoRepository<Person,String> {
Mono<Person> save(Person person);
}
我的服务:
@AllArgsConstructor
@Service
public class personServiceImpl implements personService{
personRepository repository;
@Override
public Flux<Person> findAll() {
return repository.findAll();
}
@Override
public Mono<Person> saveOrUpdate(Person person) {
CompletableFuture<Person> future = CompletableFuture.supplyAsync(() -> {
repository.save(person);
return person;
});
return Mono.fromFuture(future);
}
}
以及其余服务本身:
@RestController
@AllArgsConstructor
public class personController {
personServiceImpl personService;
@GetMapping("/all")
Flux<Person> getAllPerson(){
return personService.findAll();
}
@PostMapping("/save")
public Mono<Person> post(@RequestBody Person user) {
System.out.println("inside***************");
return personService.saveOrUpdate(user);
}
}
现在,当我想测试服务并通过 postman 保存或查找所有人时,出现错误:
"path": "/all",
"status": 405,
"error": "Method Not Allowed",
也就是我理解的,请求连函数都没有到达,直接就报错了,这里哪里会报错?
问题似乎出在 saveOrUpdate()
方法中。您实际上并不需要 CompletableFuture
(在这种情况下为什么需要?)并且以下内容应该有效:
@AllArgsConstructor
@Service
public class personServiceImpl implements personService{
personRepository repository;
@Override
public Flux<Person> findAll() {
return repository.findAll();
}
@Override
public Mono<Person> saveOrUpdate(Person person) {
return repository.save(person);
}
}
我想写第一个程序webFlux
和ReactiveMongoRepository
。
我有存储库:
@Repository
public interface personRepository extends ReactiveMongoRepository<Person,String> {
Mono<Person> save(Person person);
}
我的服务:
@AllArgsConstructor
@Service
public class personServiceImpl implements personService{
personRepository repository;
@Override
public Flux<Person> findAll() {
return repository.findAll();
}
@Override
public Mono<Person> saveOrUpdate(Person person) {
CompletableFuture<Person> future = CompletableFuture.supplyAsync(() -> {
repository.save(person);
return person;
});
return Mono.fromFuture(future);
}
}
以及其余服务本身:
@RestController
@AllArgsConstructor
public class personController {
personServiceImpl personService;
@GetMapping("/all")
Flux<Person> getAllPerson(){
return personService.findAll();
}
@PostMapping("/save")
public Mono<Person> post(@RequestBody Person user) {
System.out.println("inside***************");
return personService.saveOrUpdate(user);
}
}
现在,当我想测试服务并通过 postman 保存或查找所有人时,出现错误:
"path": "/all",
"status": 405,
"error": "Method Not Allowed",
也就是我理解的,请求连函数都没有到达,直接就报错了,这里哪里会报错?
问题似乎出在 saveOrUpdate()
方法中。您实际上并不需要 CompletableFuture
(在这种情况下为什么需要?)并且以下内容应该有效:
@AllArgsConstructor
@Service
public class personServiceImpl implements personService{
personRepository repository;
@Override
public Flux<Person> findAll() {
return repository.findAll();
}
@Override
public Mono<Person> saveOrUpdate(Person person) {
return repository.save(person);
}
}