【问题标题】:Non blocking REST with Spring Boot and Java 8使用 Spring Boot 和 Java 8 实现非阻塞 REST
【发布时间】:2017-08-04 23:29:08
【问题描述】:

我需要帮助。

我的一个端点超时的问题让我很苦恼。 我对我正在使用的 SQL 和其他 REST 服务进行了一些性能调整,但它只提供了一点帮助。 对于这个问题,我认为一个很好的解决方案是使用 Spring Boot 和 Java 8 的一些 Async 功能并执行某种“即发即弃”操作。

我尝试过类似的东西,但它并不好,“摇滚时间!”消息被打印出来了,但似乎根本没有调用 getLyrics() 方法!

    //MyController.java
    @GET
    @Path("na/na/na")
    @Produces({"application/json"})
    public Response getLyrics() {

        final String lyrics = delegate.getLyrics();
        return Response.ok().entity(lyrics.isEmpty()).build();
    }

    //MyDelegate.java
    @Async("threadPoolTaskExecutor")
    public Future<Boolean> getLyrics() {

        LOG.info("Time to rock!");
        final boolean result = lyricsService.getLyrics();
        return new AsyncResult<Boolean>(result);
    }

    //MyAsyncConfig.java
    @Configuration
    @EnableAsync
    public class MyAsyncConfig {

        @Bean(name = "threadPoolTaskExecutor")
        public Executor threadPoolTaskExecutor() {
            return new ThreadPoolTaskExecutor();
        }
    }

所以, LyricsService.getLyrics()(由于某种原因没有被调用)完成所有工作,调用其他服务,从 SQL 数据库中获取内容,并针对其他一些 REST 端点执行调用。所有这些都需要时间,有时*会导致超时。我希望它能够平静地处理,如果可能的话,尽可能返回某种响应。

我尝试了这个解决方案的几种变体,因为它似乎接近我需要的,但似乎无法理解为什么它不适合我。

*经常

【问题讨论】:

  • 告诉我当我从休息控制器返回 CompletableFuture 然后 Spring boot 使用 i/o 非阻塞?

标签: rest asynchronous spring-boot java-8 nonblocking


【解决方案1】:

我认为,春季期货必须等到操作完成。不过java completable future 更强大也许你可以试试。

Future<String> a = ...;

while(!a.isDone()){
}

这是一个示例。 https://spring.io/guides/gs/async-method/

【讨论】:

    【解决方案2】:

    您可以使用 Spring 的 DeferedResult 以及 Java8 的 Computable future 来使您的控制器非阻塞,从而在 Comupatable Future 的 whenAsync 方法中委托长时间运行的任务。这是一个工作示例 - https://github.com/kazi-imran/TransactionStatistics

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 2021-01-17
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 2019-05-31
      • 2018-05-29
      相关资源
      最近更新 更多