Aumentando a eficiência do Web Container usando           chamadas Assíncronas                  Trilha – Java         Rafa...
Agenda Web 2.0 Web Assíncrona Servlet 3.0 (JSR 315) Demo                         Globalcode – Open4education
Tuelho Trabalho com Java desde 2004   Desenvolvimento (back-end)   Infraestrutura Java JBoss.org   rhq-project (contributo...
Web interativa                 Globalcode – Open4education
Web 2.0 (mais interativa e dinâmica)                                       Globalcode – Open4education
Novas tecnologias                    Globalcode – Open4education
Novos modelos de comunicação          Client asynchronous requests                  pooling                               ...
Server busy!               Globalcode – Open4education
Comunicação HTTP thread per connection   Baseado no http 1.1 (persistent connection) thread per request model   non-blocki...
thread-per-connection                                           WebServer             Http          Connection        requ...
thread-per-request                                   WebServer     Request #1          active                       T#5   ...
Web Assíncrona: problemas emotivações Long Running Requests Real time updates                              Globalcode – Op...
Servlet 3.0: melhorias JSR 315 (2009)   Asynchronous support   Ease of configuration   Annotations   Pluggability/Modulari...
Async Context  Javax.servlet.AsyncContext.start()  “Causes the container to dispatch a thread, possibly from a  managed th...
Ciclo de uma requsiçãoassíncrona① Cliente envia uma requisição② Servidor invoca um Servlet (nova thread alocada)③ O Servle...
Processamento assíncrono                                                  WebServer                         2             ...
Sample code@WebServlet(name = "MyAsyncServlet",   urlPatterns = {"/MyAsyncServlet"}, asyncSupported = true)public class My...
JavaSE 5 ExecutorFramework                    Globalcode – Open4education
JavaSE 5 ExecutorFramework: conceitos Task    Runnable    Callable Thread Synchronous processing Asynchronous processing T...
ThreadPoolExecutor Thread pool Work queue   Bounded   Unbounded Handler (saturation policy)   Defaults: RejectedExecutionE...
Executor: main steps① Criar uma instância de Executor② Criar uma task  Runnable ou Callable③ Submeter a task para execução...
ServletContextListener@WebListenerpublic class ServletContextListener implementsjavax.servlet.ServletContextListener {   @...
MyAsyncServletprotected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletExcepti...
AsyncTask (Runnable instance)public class AsyncTask implements Runnable {   private AsyncContext asyncContext;    public A...
Demo: sync vs. async   Requisição   Servlet   Rest             Rest                                          Service      ...
… mas eu não uso servlet JEE 6   EJB @Asynchronous   CDI Events JSF Component Framework   Primefaces/RichFaces     ServerP...
Web Assíncrona:implementações Comet   Traditional pooling   Long pooling   Http Streaming WebSocket protocol Algumas imple...
DÚVIDAS?           Globalcode – Open4education
Contatos    rafaelcba@gmail.com    @rafaeltuelho    http://rafaeltuelho.net.br                                 Globalcode ...
Upcoming SlideShare
Loading in …5
×

Aumentando a eficiência do Web Container usando chamadas Assíncronas

2,915 views

Published on

Palestra apresentada na track Java do TDC2012 edição Goiânia.

  • Be the first to comment

Aumentando a eficiência do Web Container usando chamadas Assíncronas

  1. 1. Aumentando a eficiência do Web Container usando chamadas Assíncronas Trilha – Java Rafael Torres Coelho Soares (Tuelho) rafaelcba@gmail.com @rafaeltuelho Globalcode – Open4education
  2. 2. Agenda Web 2.0 Web Assíncrona Servlet 3.0 (JSR 315) Demo Globalcode – Open4education
  3. 3. Tuelho Trabalho com Java desde 2004 Desenvolvimento (back-end) Infraestrutura Java JBoss.org rhq-project (contributor) Red Hat (2010-2012) Serviços e consultoria Oracle Fusion Middleware Weblogic Application Server (consultoria) Globalcode – Open4education
  4. 4. Web interativa Globalcode – Open4education
  5. 5. Web 2.0 (mais interativa e dinâmica) Globalcode – Open4education
  6. 6. Novas tecnologias Globalcode – Open4education
  7. 7. Novos modelos de comunicação Client asynchronous requests pooling push Server events Globalcode – Open4education
  8. 8. Server busy! Globalcode – Open4education
  9. 9. Comunicação HTTP thread per connection Baseado no http 1.1 (persistent connection) thread per request model non-blocking I/O (NIO) – Java 1.4 Globalcode – Open4education
  10. 10. thread-per-connection WebServer Http Connection request active T#5 response Http Thread Pool T# T# T# 1 2 3 Keep alive timeout… ou T# T# 5 T# Connection timeout 4 6 idle Connection Queue C1 c1 c1 (backlog) c1 C# # Globalcode – Open4education
  11. 11. thread-per-request WebServer Request #1 active T#5 Response #1 Response time… Http Thread Pool T# T# T# 1 2 3 request #2 T# T# 5 T# T#1 4 6 idle Response #2 Connection Queue C1 c1 c1 (backlog) c1 C# # Globalcode – Open4education
  12. 12. Web Assíncrona: problemas emotivações Long Running Requests Real time updates Globalcode – Open4education
  13. 13. Servlet 3.0: melhorias JSR 315 (2009) Asynchronous support Ease of configuration Annotations Pluggability/Modularization: web fragments Enhancements to existing APIs Globalcode – Open4education
  14. 14. Async Context Javax.servlet.AsyncContext.start() “Causes the container to dispatch a thread, possibly from a managed thread pool, to run the specified Runnable.”e daí? O que faço com isso? Globalcode – Open4education
  15. 15. Ciclo de uma requsiçãoassíncrona① Cliente envia uma requisição② Servidor invoca um Servlet (nova thread alocada)③ O Servlet invoca request.startAsync(), salva AsyncContext, e retorna④ A thread alocada é liberada, mas o response permanece aberto⑤ Outra thread (pool separado) utiliza o AsyncContext para concluir a resposta (asyncContext.complete() ou asyncContext.dispatch())⑥ Cliente recebe a resposta do servidor. Globalcode – Open4education
  16. 16. Processamento assíncrono WebServer 2 1 Request active Servlet Context T#5 3 request.startAsync() Managed Thread Pool 5 asyncContext.complete() Response 6 Http Thread Pool T# T# T# 2 3 5 4 T# T# 4 6 idle Globalcode – Open4education
  17. 17. Sample code@WebServlet(name = "MyAsyncServlet", urlPatterns = {"/MyAsyncServlet"}, asyncSupported = true)public class MyAsyncServlet extends HttpServlet {public void doGet(...) { final AsyncContext asyncContext = request.startAsync(); asyncContext.start(new Runnable(){ @ Override public void run() { // do some work here which involves waiting ... asyncContext.complete(); } }); Globalcode – Open4education
  18. 18. JavaSE 5 ExecutorFramework Globalcode – Open4education
  19. 19. JavaSE 5 ExecutorFramework: conceitos Task Runnable Callable Thread Synchronous processing Asynchronous processing Thread pool ExecutorService ThreadPoolExecutor SchedulePoolExecutor Globalcode – Open4education
  20. 20. ThreadPoolExecutor Thread pool Work queue Bounded Unbounded Handler (saturation policy) Defaults: RejectedExecutionException runtime exception Thread Factory Globalcode – Open4education
  21. 21. Executor: main steps① Criar uma instância de Executor② Criar uma task Runnable ou Callable③ Submeter a task para execução④ Executar a task⑤ Finalizar o Executor Globalcode – Open4education
  22. 22. ServletContextListener@WebListenerpublic class ServletContextListener implementsjavax.servlet.ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { Executor executor = new ThreadPoolExecutor(10, 100, 60000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100)); sce.getServletContext(). setAttribute("threadPoolExecutor", executor); } @Override public void contextDestroyed(ServletContextEvent sce) { ThreadPoolExecutor executor = (ThreadPoolExecutor)sce.getServletContext() .getAttribute("threadPoolExecutor"); executor.shutdownNow(); }} Globalcode – Open4education
  23. 23. MyAsyncServletprotected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { try { AsyncContext asyncCtx = request.startAsync(); ThreadPoolExecutor executor = (ThreadPoolExecutor) request.getServletContext(). getAttribute("threadPoolExecutor"); asyncCtx.setTimeout(-1L); asyncCtx.addListener(new ServletAsyncListener()); //delegate long running process to an "async" thread executor.execute(new AsyncTask(asyncCtx)); } finally { }} Globalcode – Open4education
  24. 24. AsyncTask (Runnable instance)public class AsyncTask implements Runnable { private AsyncContext asyncContext; public AsyncTask(AsyncContext asyncContext) { this.asyncContext = asyncContext; } @Override public void run() { // acesso remoto, query, processamento pesado // escreve na resposta… asyncContext.complete(); // ou asyncContext.dispatch(); }} Globalcode – Open4education
  25. 25. Demo: sync vs. async Requisição Servlet Rest Rest Service Globalcode – Open4education
  26. 26. … mas eu não uso servlet JEE 6 EJB @Asynchronous CDI Events JSF Component Framework Primefaces/RichFaces ServerPush com Atmosphere Ajax Pooling JEE 7 Java Websocket Spec (JSR 356) Globalcode – Open4education
  27. 27. Web Assíncrona:implementações Comet Traditional pooling Long pooling Http Streaming WebSocket protocol Algumas implementações alternativas Atmosphere Framework (github.com/Atmosphere/) Tomcat: CometProcessor class Jetty 6: Continuations Grizzly (glassfish): CometEngine class. Globalcode – Open4education
  28. 28. DÚVIDAS? Globalcode – Open4education
  29. 29. Contatos rafaelcba@gmail.com @rafaeltuelho http://rafaeltuelho.net.br Globalcode – Open4education

×