同步异步处理对比
- 使用Callable进行异步处理,副线程写在主线程里面的 ,符合企业级开发的一般应用场景!AsyncController.java
package com.imooc.web.asnyc;
import java.util.concurrent.Callable;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
@RestController
public class AsyncController {
private Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping("/order")
public Callable<String> order() throws Exception {
logger.info("主线程开启");
Callable<String> result = new Callable<String>() {
@Override
public String call() throws Exception {
logger.info("副线程开启");
Thread.sleep(1000);
logger.info("副线程关闭");
return "success";
}
};
logger.info("主线程关闭");
return result;
}
}
运行结果:
- 使用DefferedResult异步处理Rest服务,符合企业级开发的复杂应用场景!