Temat: servlet asynchroniczny
Temat: | servlet asynchroniczny |
Data: | 2013-01-24 |
Treść: |
Poniżej przedstawiony jest prosty przykład wykorzystania asynchroniczności w servlet 3.0. Servlet zwraca response, gdzie w tle wykonuje się przez 10 sekund wątek. Servlet: package pl.test.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns="/AsyncServlet", asyncSupported=true) public class AsyncServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss"); AsyncContext async = req.startAsync(req, res); res.getWriter().write("start "+simpleDateFormat.format(new Date())+""); async.setTimeout(1); res.setHeader("id", String.valueOf(new Random().nextInt())); async.start(new Work(res)); res.getWriter().write("stop "+simpleDateFormat.format(new Date())); } } package pl.test.servlet; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletResponse; public class Work implements Runnable { SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss"); HttpServletResponse res; String watek; public Work(HttpServletResponse res) { this.res=res; } @Override public void run() { watek=res.getHeader("id"); System.out.println("start pracy watku " + watek + " " +simpleDateFormat.format(new Date())); try { Thread.sleep(10*1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("po pracy watku " + watek + " " +simpleDateFormat.format(new Date())); } } |
<< Powrót << |
powered by sw