springmvc不断输出文本到网页

背景

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

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一下web

➜  ~ 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貌似看不到效果浏览器


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

图片描述

相关文章
相关标签/搜索