如何使Data REST存储库方法异步

时间:2018-11-14 07:08:01

标签: java spring-boot spring-data-jpa spring-data spring-data-rest

是否可以通过@RepositoryRestResource注释异步将存储库作为其余资源公开?或者换句话说,我希望保存,查找等方法是异步的,而ResponseEntityController也会将它们作为异步调用来处理?

如果我只是将存储库标记为同步,那么我的POST请求就会失败,因为ResponseEntityController上的此方法将无法处理存储库的异步持久调用

private ResponseEntity<ResourceSupport> createAndReturn(Object domainObject, RepositoryInvoker invoker,
        PersistentEntityResourceAssembler assembler, boolean returnBody) {

    publisher.publishEvent(new BeforeCreateEvent(domainObject));
    Object savedObject = invoker.invokeSave(domainObject);
    publisher.publishEvent(new AfterCreateEvent(savedObject));

    Optional<PersistentEntityResource> resource = Optional
            .ofNullable(returnBody ? assembler.toFullResource(savedObject) : null);

    HttpHeaders headers = headersPreparer.prepareHeaders(resource);
    addLocationHeader(headers, assembler, savedObject);

    return ControllerUtils.toResponseEntity(HttpStatus.CREATED, headers, resource);
}

这是我的资料库

@RepositoryRestResource(path = "companies", collectionResourceRel = "companies")
public interface CompanyRepository extends CrudRepository<Company, Long> {

    @Override
    @RestResource(exported = false)
    void delete(Company entity);

    @Override
    @RestResource(exported = false)
    void deleteById(Long id);

    @Override
    @RestResource(exported = false)
    void deleteAll();

    @Override
    @RestResource(exported = false)
    void deleteAll(Iterable<? extends Company> entities);
}

1 个答案:

答案 0 :(得分:0)

我发现的唯一方法是坚持使用Spring Data JPA并编写自己的HATEOAS控制器,该控制器返回CompletableFutrues,这些CompletableFutrues调用从JPA存储库返回的值中组合HATEAOS资源的服务。然后,可以使用线程池执行程序或并发执行程序等使Service to Service和Service to JPA Repository控制器异步。