BigPipe(FaceBook使用的页面加载技术) JAVA实现代码示例

代码如下:在使用队列方面没有仔细斟酌,随便找一个过来,就用了。

注意一点,就是不要把 PrintWriter 的实例对象拿到多线程里去用,否则会出莫名其妙的异常。

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BigPipeServlet extends HttpServlet {

    private static ExecutorService executor = Executors.newFixedThreadPool(50);

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<String>(6);

        for (int i = 0; i < 6; i++) {
            final int id = i + 1;

            executor.execute(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep((int) (Math.random() * 10000));
                        q.put(pagelet("content" + id, "Wohooo" + id));
                    } catch (InterruptedException e) {
                    }
                }
            });
        }

        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        out
                .println("<html><head>"
                        + "<script type=\"text/javascript\">function arrived(id,text) { var b=document.getElementById(id); b.innerHTML = text; }</script>"
                        + "</head><body>" + "<div>Progressive Loading");
        content(out, "content1", "content2", "content3", "content4", "content5", "content6");
        out.println("</div>");

        for (int i = 0; i < 6; i++) {
            try {
                out.println(q.take());
                out.flush();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        out.println("</body></html>");
    }

    private void content(PrintWriter writer, String... contentIds) {
        for (String id : contentIds) {
            writer.println("<div id=\"" + id + "\">-</div>");
        }
    }

    private String pagelet(String id, String content) {
        return "<script>" + "arrived(\"" + id + "\", \"" + content + "\");" + "</script>";
    }
}

你可能感兴趣的:(页面加载,java实现,Facebook,bigpipe)