上一篇文章写了基于Servlet 的HTTP异步服务,这一章我们来说说基于DeferredResult的异步服务。
- 在pom.xml中引入配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 建立Service层接口
public interface PiceaService {
//无返回参数方法
void task() throws Exception;
//有返回参数方法
String task2() throws Exception;
}
- 建立Service层实现
Service层接口与实现,跟其他正常同步请求一样,没有差别。
@Service
public class PiceaServiceImpl implements PiceaService {
@Override
public void task() throws Exception {
System.out.println("------------------------在看貂蝉,不要打扰--------------");
Thread.sleep(1000);
}
@Override
public String task2 () throws Exception {
int k = 1;
System.out.println("------------------------在看鱼,不要打扰--------------");
Thread.sleep(1000);
return (String.valueOf(k));
}
}
- 建立Contoller层方法
这是重点和核心,首先要定义一个线程池来处理异步的任务。然后就是编写异步的调用方法。
@RestController
public class PiceaServletContoller {
@Autowired
private PiceaService piceaService;
@RequestMapping("/deferredresult")
public DeferredResult<String> deferredResult() throws Exception {
System.out.println("控制层执行线程:" + Thread.currentThread().getName());
//超时
DeferredResult<String> deferredResult = new DeferredResult<String>(10*1000L);
deferredResult.onTimeout(new Runnable() {
@Override
public void run() {
System.out.println("异步线程执行超时");
deferredResult.setResult("线程执行超时");
}
});
deferredResult.onCompletion(new Runnable() {
@Override
public void run() {
System.out.println("异步执行完毕");
}
});
FIXED_THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
System.out.println("异步执行线程:" + Thread.currentThread().getName());
try {
String str = piceaService.task2();
Thread.sleep(1000);
deferredResult.setResult("这是【异步】的请求返回: " + str);
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
});
return deferredResult;
}
/**
* 线程池
*/
public static ExecutorService FIXED_THREAD_POOL = Executors.newFixedThreadPool(10);
}
- 测试结果及方法
浏览器中访问http://localhost:2001/deferredresult测试结果。
Spring-boot-async-deferredResult.png
其它注意
本文章样例:
工程名:spring-boot-async-deferredresult
GitHub:https://github.com/zzyjb/SpringBootLearning
网友评论