springmvc不断输出文本到网页

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貌似看不到效果


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

图片描述


如果觉得我的文章对你有用,请随意赞赏

你可能感兴趣的

载入中...