何时使用 Spring @Async vs Callable 控制器(异步控制器,servlet 3) [英] When to use Spring @Async vs Callable controller (async controller, servlet 3)

查看:25
本文介绍了何时使用 Spring @Async vs Callable 控制器(异步控制器,servlet 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 Spring 中使用 Callable 使用 @Async 和 Servlet 3 异步请求实现的一般用例.

I would like to know the general use case of using @Async and Servlet 3 asynchronous request implementation in Spring using Callable.

据我所知,@Async 用于使任何方法(特别是任何服务方法)异步执行.

As I understand, @Async is for making any method (specifically, any service method) execute asynchronously.

@Async
void doSomething(String s) {
// this will be executed asynchronously
}

以及任何返回 Callable 的控制器

and any controller which returns Callable

  @RequestMapping("/view")
public Callable<String> callableWithView(final Model model) {
    return new Callable<String>() {
        @Override
        public String call() throws Exception {
            Thread.sleep(2000);
            model.addAttribute("foo", "bar");
            model.addAttribute("fruit", "apple");
            return "views/html";
        }
    };
}

我对何时使用什么感到困惑.使用Asynchronous servlet/controller和spring @Async一起使用会有什么效果?

I am confused on whento use what. What will be the effect of using Asynchronous servlet/controller and with spring @Async together?

推荐答案

这篇 文章解释了你在找什么

This post has explanation for what you are looking for

摘录:

在某些情况下,您可以立即返回给客户后台作业完成处理.例如发送电子邮件,启动数据库工作,而其他人则代表一劳永逸可以使用 Spring 的 @Async 支持或通过将事件发布到 Spring Integration 频道,然后返回一个客户端可用于查询结果的确认 ID.

In some cases you can return to the client immediately while a background job completes processing. For example sending an email, kicking off a database job, and others represent fire-and-forget scenarios that can be handled with Spring's @Async support or by posting an event to a Spring Integration channel and then returning a confirmation id the client can use to query for the results.

可调用返回类型使控制器方法异步.这通常用于长轮询等情况.阅读这个 同一作者的帖子以获取更多信息.

Callable return type makes a controller method asynchronous. This is usually used in situations like long polling. Read this post by the same author for more information.

Callable 也是 Runnable 的替代品,从某种意义上说,它可以返回结果并抛出已检查的异常.

Also callable is an alternative for Runnable, in the sense, It can return results and throw checked exceptions.

说你有一个方法

public String aMethod(){

}

这可以通过简单地返回一个 Callable 接口来实现异步.

This can be made asynchronous by simply returning a Callable interface.

public Callable<String>  aMethod(){

}

这篇关于何时使用 Spring @Async vs Callable 控制器(异步控制器,servlet 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆