spring中Response如何采用异步运行,Controller快速返回呢?
下文笔者讲述Response中异步返回的方法及示例分享
SpringBoot中的Controller编写以下代码,即可直接返回,然后异步运行
异步返回需求的说明:
今天使用Controller编写一个接口时
发现接口中的逻辑运行时间非常长
那么有没有办法让接口快速返回,业务逻辑继续向下运行
实现思路:
方式1:
使用一个消息队列接收逻辑运行指令
使Controller快速返回
方式2:
让Controller的response快速返回
业务逻辑继续向下运行
此时客户端已经收到反馈
只是代码还在向下运行
例:SpringBoot中的Controller编写以下代码,即可直接返回,然后异步运行
ServletOutputStream out = response.getOutputStream();
JSONObject resultmap = new JSONObject();
resultmap.put("result", "8888888");
byte[] resultBytes = resultmap.toString().getBytes();//二进制转化
out.write(resultBytes);//返回客户端
out.close();//关闭流,切记!
例:
@RequestMapping("/test")
public int test(@RequestBody test model,HttpservletResponse response) throws Exception {
ServletOutputstream out = response.getOutputStream();
JsoNobject resultmap = new JsoNobject();
resultmap.put("result","232323232323");
byte[] resultBytes = resultmap.tostring() .getBytes();out.write(resultBytes);
out.close();
if (null == model)
throw BadRequestException.le("test")
return catalogService.test222(model);
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


