【问题标题】:returning value before @Async funtion is complete在 @Async 函数完成之前返回值
【发布时间】:2015-01-02 09:58:42
【问题描述】:

您好,我有一个控制器需要在另一个控制器完成之前调用另一个控制器并返回一个值。

@EnableAsync
@Controller
public class InitController {
    private static final Logger logger = LoggerFactory
            .getLogger(InitController.class);
    @Value("${init.hostname}")
    private String base_url;

    @RequestMapping(value = "/rest/init/{id}", method = RequestMethod.GET)
    public @ResponseBody
    String initialize(@PathVariable String id) throws Fault_Exception {
    try {
        Future<String> result = customerAsync(id);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        return null;

    }

    @Async
    private Future<String> customerAsync(String id) throws Fault_Exception, IOException{


        URL url = new URL(base_url + "rest/customer/" + id);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        if (conn.getResponseCode() != 200 ) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

        conn.disconnect();
        return new AsyncResult<String>(null);
    }


}

现在发生的情况是,当我调用 InitController 时,它会在返回 null 之前等待,直到 /rest/customer/ 控制器完成。

【问题讨论】:

    标签: java spring spring-mvc asynchronous controller


    【解决方案1】:

    除非您使用 aspectj,否则 Spring 不会为私有方法创建代理,因此在您的示例中,customerAsync 方法是同步调用的。

    解决问题的最简单方法是提取customerAsync 方法来分离@Component 带注释的类。

    另外,@EnableAsync 注释应该用在@Configuration 类而不是控制器上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 2020-04-09
      • 2018-02-08
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 2014-08-25
      相关资源
      最近更新 更多