1

背景

有一些批处理的东东,后台执行可能超时,如果等最后遇到错误或者有什么结果才返回,往往会超时,而且整个执行过程的细节也都没法看到,是个黑盒,不大方面调试。这里讲一下如果实现类似websocket的效果,就是后端不断往流里头写文本。

controller

@Controller
@RequestMapping("/echo")
public class EchoController {

    @RequestMapping(value = "/reply",method = RequestMethod.GET)
    public void writeStream(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/html;charset=utf-8");
        for(int i=0;i<1000;i++){
            write(response,"hello");
            Thread.sleep(1000*2);
            System.out.println("send");
        }

        response.getWriter().close();
    }

    private void write(HttpServletResponse response,String content) throws IOException {
        response.getWriter().write(content+"<br/>");
        response.flushBuffer();
        response.getWriter().flush();
    }
}

运行

➜  ~ wget http://localhost:8080/echo/reply
--2017-06-14 16:08:14--  http://localhost:8080/echo/reply
Resolving localhost... ::1, 127.0.0.1
Connecting to localhost|::1|:8080... connected.
HTTP request sent, awaiting response... 200
Length: unspecified [text/html]
Saving to: 'reply'

reply                   [     <=>            ]      60  5.99 B/s

然后tail一下

➜  ~ tail -f reply
hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>hello<br/>

或者用浏览器访问就可以看到效果了.

直接curl貌似看不到效果


想获取最新内容,请关注微信公众号

图片描述


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...


引用和评论

0 条评论