SlideShare una empresa de Scribd logo
1 de 98
Descargar para leer sin conexión
Open a Window, see the clouds




                         Rafael Dohms   photo credit: Denis Grzetic

Saturday, July 9, 2011
Rafael Dohms




                                                               photo credit: Eli White
        Evangelista PHP, membro ativo da Comunidade
        PHP e certificado ZCE. Ele ajudou na fundação de
        dois Grupos de Usuários de PHP ao longo do tempo
        e hoje compartilha a coordenação do PHPSP.
        Desenvolvedor, gamer e apaixonado por código ele
        também é host do primeiro podcast de PHP do
        Brasil: PHPSPCast.

        Atualmente ele trabalha na equipe SWAT do
        grupo MIH, uma equipe de experts que fornecem
        conhecimento técnico para o grupo além de trabalhar
        com P&D buscando novos nichos da internet e
        tecnologia. Seu papel como Desenvolvedor
        Sênior é codar, treinar e auxiliar outras empresas e
        se divertir enquanto faz isso.


Saturday, July 9, 2011
OLHANDO PELA JANELA


    •O          que é a nuvem?

    • Por                que escolher a nuvem?

    • Vamos               conhecer o Windows Azure

    • Como                isso vai afetar meu código?



Saturday, July 9, 2011
O QUE É A NUVEM?
                         não é só mais uma palavra no buzzword bingo

Saturday, July 9, 2011
HOSPEDAGEM COMUM


    • Conta   compatilhada, VPS ou
        máquina local

    • Uma                máquina, um local

    • Pagamento               mensal



Saturday, July 9, 2011
Própria
              HOSPEDAGEM COMUM


    • Conta   compatilhada, VPS ou
        máquina local

    • Uma                máquina, um local

    • Pagamento               mensal



Saturday, July 9, 2011
COMPUTAÇÃO NA NUVEM

    •   Menos “apego físico” (virtualização)

    •   Uma ou mais máquinas ou
        “instancias”

    •   Geograficamente espalhada

    •   Pagamento por hora/recurso

    •   “abstração” de recursos

    •   3 Sabores: IaaS, PaaS, SaaS

Saturday, July 9, 2011
Dados



                              Aplicação



                              Software



                         Sistema Operacional



                           Hardware/Rede


Saturday, July 9, 2011
Armazenamento                          Dados           Compartilhar


               Publicação             Aplicação        Desenvolvimento


                         MySQL        Software         Apache


       Configuração              Sistema Operacional   Upgrades


       Resfriamento                Hardware/Rede       Cabeamento

Saturday, July 9, 2011
IaaS a Service”
                         “Infrastructure as
                         “Infraestrutura como Serviço”
                                     Dados

                                    Aplicação

                                    Software

                               Sistema Operacional

                                 Hardware/Rede




Saturday, July 9, 2011
IaaS a Service”
                         “Infrastructure as
                         “Infraestrutura como Serviço”
                                     Dados

                                    Aplicação

                                    Software

                               Sistema Operacional       você
                                                         eles
                                 Hardware/Rede




Saturday, July 9, 2011
PaaS
                           “Platform as a Service”
                         “Plataforma como Serviço”
                                    Dados

                                   Aplicação

                                   Software

                              Sistema Operacional

                                Hardware/Rede




Saturday, July 9, 2011
PaaS
                           “Platform as a Service”
                         “Plataforma como Serviço”
                                    Dados

                                   Aplicação         você
                                                     eles
                                   Software

                              Sistema Operacional

                                Hardware/Rede




Saturday, July 9, 2011
SaaS
                          “Software as a Service”
                         “Software como Serviço”
                                   Dados

                                  Aplicação

                                  Software

                             Sistema Operacional

                               Hardware/Rede




Saturday, July 9, 2011
SaaS
                          “Software as a Service”
                         “Software como Serviço”
                                   Dados            você
                                                    eles
                                  Aplicação

                                  Software

                             Sistema Operacional

                               Hardware/Rede




Saturday, July 9, 2011
X
       POR QUE ESCOLHER A NUVEM?
                         Quais são as vantagens de escolher a nuvem?

Saturday, July 9, 2011
trafego




                           tempo




         O MODELO CONTA DE LUZ
Saturday, July 9, 2011
trafego




                           tempo




         O MODELO CONTA DE LUZ
Saturday, July 9, 2011
trafego



              pico




                           tempo




         O MODELO CONTA DE LUZ
Saturday, July 9, 2011
trafego



              pico




                           tempo




         O MODELO CONTA DE LUZ
Saturday, July 9, 2011
trafego



              pico




                           tempo




         O MODELO CONTA DE LUZ
Saturday, July 9, 2011
IaaS   Paas   SaaS

                                  custos



                   gerenciamento do
                          servidor



                   gerenciamento do
                          software



                         publicação da
                               aplicação


Saturday, July 9, 2011
DISPONIBILIDADE
Saturday, July 9, 2011
DISPONIBILIDADE
Saturday, July 9, 2011
DISPONIBILIDADE
Saturday, July 9, 2011
ESCALABILIDADE
            Computação sem estado + Armazenamento durável
Saturday, July 9, 2011
ESCALABILIDADE
            Computação sem estado + Armazenamento durável
Saturday, July 9, 2011
OLHANDO POR DENTRO

Saturday, July 9, 2011
Windows Azure


                                         Fabric


                               Compute            Storage




Saturday, July 9, 2011
Fabric
                         Middleware, usado para desenvolver, testar, publicar e
                                       gerenciar sua aplicação.




                                   AppFabric

         developer




Saturday, July 9, 2011
Fabric


                         Compute            Storage




Saturday, July 9, 2011
Compute




                         Web Role   Worker Role           VM Role

                                                       Máquina virtual de
                   Aplicação Web
                                    Processamento em   Windows Server
                  rodando sobre o
                                      plano de fundo    2008 carregada
                         IIS
                                                         sob demanda




Saturday, July 9, 2011
Fabric


                         Compute            Storage




Saturday, July 9, 2011
Versão cacheada de
                                                       CDN          qualquer recurso
                                                                      com uma URI
                                          Storage



    Armazenamento de dados


      Table Storage          Blob Storage       SQL Azure             Queue

                                                                      Troca de
       Armazenamento          Texto e dados    Compatível com o
                                                                  mensagens entre o
         estruturado             binários        SQL Server
                                                                  Web e o Worker




Saturday, July 9, 2011
PRONTO PRA RODAR
                                    para Desenvolver e Publicar


    • Requisitos:

          • IIS7         e ferramentas

          • Azure  SDK (instala o DevAppFabric, o simulador de
              azure)

          • Command            Line Tools (linha de comando)

               • Command         line tools for PHP

Saturday, July 9, 2011
CAIXA DE FERRAMENTAS

    • Command                Line tools for PHP

          • Cria o pacote da aplicação e roda no emulador, simulando o
              computacional e o armazenamento.

    • Azure              Tools para Eclipse

          • Torna  a maioria dos processos “next, next finish” e fornece
              uma IDE completa.


Saturday, July 9, 2011
Ambiente do Desenvolvedor
                               Simulador Azure                 Código
                                 (Dev fabric)



                                 Ferramentas de empacotamento
                                  (linha de comando ou eclipse)
        Pacote + Configuração
              do Serviço



                                             Azure




                                                                        Window Azure
                                           (AppFabric)




                                 SQLAzure                Storage

Saturday, July 9, 2011
Ambiente do Desenvolvedor
                               Simulador Azure                 Código
                                 (Dev fabric)


                         PHP
                                 Ferramentas de empacotamento
                                  (linha de comando ou eclipse)
        Pacote + Configuração
              do Serviço



                                             Azure




                                                                        Window Azure
                                           (AppFabric)




                                 SQLAzure                Storage

Saturday, July 9, 2011
Ambiente do Desenvolvedor
                               Simulador Azure                 Código
                                 (Dev fabric)


                         PHP
                                 Ferramentas de empacotamento
                                  (linha de comando ou eclipse)
        Pacote + Configuração
              do Serviço



                                             Azure




                                                                        Window Azure
                                           (AppFabric)




                                 SQLAzure                Storage

Saturday, July 9, 2011
Ambiente do Desenvolvedor
                                         Simulador Azure                 Código
                                           (Dev fabric)


                          php package.php
                         PHP
                          --project="twitter-azure"
                                               Ferramentas de empacotamento
                          --target="c:azure-build" de comando ou eclipse)
                                                 (linha
                          --source="C:twitter-azure"
        Pacote + Configuração
              do Serviço --defaultDoc="public/index.php"
                          --phpRuntime="C:Program Files (x86)PHPv5.3"
                          --cleanRebuild
                          --runDevFabric                   Azure




                                                                                  Window Azure
                                                     (AppFabric)




                                            SQLAzure               Storage

Saturday, July 9, 2011
Ambiente do Desenvolvedor
                               Simulador Azure                 Código
                                 (Dev fabric)


                         PHP
                                 Ferramentas de empacotamento
                                  (linha de comando ou eclipse)
        Pacote + Configuração
              do Serviço



                                             Azure




                                                                        Window Azure
                                           (AppFabric)




                                 SQLAzure                Storage

Saturday, July 9, 2011
O BOM

    • APIs               em REST

          • Armazenamento

          • Diagnósticos

    • BD             Relacional: SQL Azure

    • Arquitetura            por “Roles”


Saturday, July 9, 2011
O RUIM

    • Gerenciamento      apenas
        pelo Windows

          • Sem    Emulador Azure
              para SO não-Windows

          • Sem   ferramentas de
              empacotamento para
              SO não-Windows


Saturday, July 9, 2011
COMO ISSO AFETA MEU CÓDIGO?
          Que ferramentas podemos usar e como devemos desenhar
                            nossas aplicações?
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




                 Código
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




                 Código   PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




           Arquitetura


                 Código   PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




    Escalando a
     aplicação

           Arquitetura


                 Código   PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




    Escalando a           Sem Armazenamento
     aplicação                  Local

           Arquitetura


                 Código       PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




    Escalando a           Sem Armazenamento     Compartilhamento
                                Local              de sessão
     aplicação

           Arquitetura


                 Código       PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




    Escalando a           Sem Armazenamento     Compartilhamento
                                Local              de sessão
     aplicação
                            Worker Roles
           Arquitetura


                 Código       PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




    Escalando a           Sem Armazenamento     Compartilhamento
                                Local              de sessão
     aplicação
                            Worker Roles         Filas
           Arquitetura


                 Código       PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?




     Armazenamento

    Escalando a           Sem Armazenamento     Compartilhamento
                                Local              de sessão
     aplicação
                            Worker Roles         Filas
           Arquitetura


                 Código       PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?


                    Que tipo?

     Armazenamento

    Escalando a                 Sem Armazenamento     Compartilhamento
                                      Local              de sessão
     aplicação
                                  Worker Roles         Filas
           Arquitetura


                 Código             PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?

                                   Tabela / Blob
                    Que tipo?

     Armazenamento

    Escalando a                 Sem Armazenamento     Compartilhamento
                                      Local              de sessão
     aplicação
                                  Worker Roles         Filas
           Arquitetura


                 Código             PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?

                                   Tabela / Blob    Framework ou PHP SDK

                    Que tipo?

     Armazenamento

    Escalando a                 Sem Armazenamento        Compartilhamento
                                      Local                 de sessão
     aplicação
                                  Worker Roles            Filas
           Arquitetura


                 Código             PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?

                                   Tabela / Blob    Framework ou PHP SDK

                    Que tipo?
                                    Banco de
                                     Dados
     Armazenamento                  Relacional

    Escalando a                 Sem Armazenamento        Compartilhamento
                                      Local                 de sessão
     aplicação
                                  Worker Roles            Filas
           Arquitetura


                 Código             PHP rodando no IIS/Windows
Saturday, July 9, 2011
COM O QUE DEVO ME PREOCUPAR?

                                   Tabela / Blob    Framework ou PHP SDK

                    Que tipo?
                                    Banco de        Migrar para SQL Azure
                                     Dados
     Armazenamento                  Relacional

    Escalando a                 Sem Armazenamento         Compartilhamento
                                      Local                  de sessão
     aplicação
                                  Worker Roles             Filas
           Arquitetura


                 Código             PHP rodando no IIS/Windows
Saturday, July 9, 2011
FRAMEWORKS PRONTOS
                       PARA O AZURE
Saturday, July 9, 2011
O QUE FAZ ELE SER
                           COMPATÍVEL?
                    Código     Roda usando PHP no Windows?

              Ferramentas         Tem wrappers das APIs?

        Banco de Dados        É compatível com MS SQL Server?



Saturday, July 9, 2011
Ferramentas
    •   Blobs, Tables e Queues
        (operações CRUD)

    •   Classes auxiliares para
        transporte HTTP, AuthN/
        AuthZ, REST and
        Gerenciamento de Erros

    •   Gerenciamento,
        Instrumentação e supporte a
        logs
       Banco de Dados

    •   Não testado, mas deve
        funcionar.

Saturday, July 9, 2011
Banco de Dados

    • Drivers  de MS-SQL* são
        compatíveis com
        SQLAzure

     * Usando pdo_sql_server, possivelmente o pdo_dblib




                                            Powered by Doctrine:



Saturday, July 9, 2011
• PHP     roda normalmente
              no Azure, qualquer
              framework vai
              funcionar.

          • Outras     ferramentas
              para se comunicar com
              recursos como: BD, Filas
              etc...

          • Estes aqui já foram
              testados!


Saturday, July 9, 2011
AZURE PHP SDK

    • Serviços:

          • Blob         Storage

          • Table         Storage

          • Queue          Storage

          • Diagnostic Tools

    • Compatível            com PHP 5+

Saturday, July 9, 2011
SAINDO PELA JANELA
                              Aplicação de teste para ilustrar


    • Aplicação           de teste: “Twitter RT Calculator”

    • Objetivo:      Analisar sues últimos tweets, verificar quais foram
        re-tuitados e fazer cálculos baseado em palavras e localizações.

    • Exemplificar           a migração:

          • Banco        de dados: MySQL > SQLAzure

          • Mover        o processamento para um Worker Role e usar a Fila

Saturday, July 9, 2011
SAINDO PELA JANELA
                              Aplicação de teste para ilustrar


    • Aplicação           de teste: “Twitter RT Calculator”

    • Objetivo:      Analisar sues últimos tweets, verificar quais foram
        re-tuitados e fazer cálculos baseado em palavras e localizações.

    • Exemplificar           a migração:

          • Banco        de dados: MySQL > SQLAzure

          • Mover        o processamento para um Worker Role e usar a Fila

Saturday, July 9, 2011
Twitter OAuth




                           Segura ai..




Saturday, July 9, 2011
Twitter OAuth




                           Segura ai..




Saturday, July 9, 2011
Twitter OAuth




                           Segura ai..




Saturday, July 9, 2011
Twitter OAuth




                           Segura ai..




                                         MySQL




Saturday, July 9, 2011
Twitter OAuth




                           Segura ai..




                                         MySQL


                          Resultados


Saturday, July 9, 2011
Twitter OAuth




                           Segura ai..




                                         MySQL


                          Resultados


Saturday, July 9, 2011
Twitter OAuth




                           Segura ai..




                                         MySQL


                          Resultados


Saturday, July 9, 2011
Twitter OAuth




                         Te ligo mais tarde..




Saturday, July 9, 2011
Twitter OAuth




                                                Queue


                         Te ligo mais tarde..




Saturday, July 9, 2011
Twitter OAuth




                                                Queue


                         Te ligo mais tarde..




                                                        Worker




Saturday, July 9, 2011
Twitter OAuth




                                                Queue


                         Te ligo mais tarde..




                                                        Worker




Saturday, July 9, 2011
Twitter OAuth




                                                Queue


                         Te ligo mais tarde..




                                                        Worker




Saturday, July 9, 2011
Twitter OAuth




                                                Queue


                         Te ligo mais tarde..




                                                                   Worker




                                                        SQLAzure
Saturday, July 9, 2011
Twitter OAuth




                                                Queue


                         Te ligo mais tarde..




                                                                   Worker




                                                        SQLAzure
Saturday, July 9, 2011
Twitter OAuth




                                                Queue


                         Te ligo mais tarde..




                                                                   Worker




                             Resultados

                                                        SQLAzure
Saturday, July 9, 2011
Twitter OAuth




                                                Queue


                         Te ligo mais tarde..




                                                                   Worker
                                                                   Worker
                                                                    Worker
                                                                    Worker
                                                                     Worker
                                                                      Worker
                                                                       Worker
                                                                       Worker
                                                                        Worker
                                                                          Worker
                                                                          Worker




                             Resultados

                                                        SQLAzure
Saturday, July 9, 2011
USANDO SQLAZURE
                                                                     PDO MSSQL Driver

                         doctrine.dbal.connection_options:
                             driver: pdo_sqlsrv
                             dbname: twitter-sample-app
                             host: pl69qjwy8k.database.windows.net
                             port: 1433
                             user: rdohmsDemo@pl69qjwy8k
                             password: *password*




Saturday, July 9, 2011
TODOS PARA A FILA
                         //Add user to our Queue
                         $qItem = new stdClass();
                         $qItem->twitter_handle = $twitterInfo->screen_name;

                         $qManager = new AzureQueue($this->getApp()->getConfig('azure'));
                         $qManager->addToQueue($qItem);




Saturday, July 9, 2011
TODOS PARA A FILA
                         //Add user to our Queue
                         $qItem = new stdClass();
                         $qItem->twitter_handle = $twitterInfo->screen_name;

                         $qManager = new AzureQueue($this->getApp()->getConfig('azure'));
                         $qManager->addToQueue($qItem);




                         $this->client = new Zend_Service_WindowsAzure_Storage_Queue(
                                 $qConfig['host'], $qConfig['accountName'], $qConfig['accountKey']
                         );

                         $this->queue = $this->getQueueInstance($queueName);
                                                                                         __contruct()




Saturday, July 9, 2011
TODOS PARA A FILA
                            //Add user to our Queue
                            $qItem = new stdClass();
                            $qItem->twitter_handle = $twitterInfo->screen_name;

                            $qManager = new AzureQueue($this->getApp()->getConfig('azure'));
                            $qManager->addToQueue($qItem);




                            $this->client = new Zend_Service_WindowsAzure_Storage_Queue(
                                    $qConfig['host'], $qConfig['accountName'], $qConfig['accountKey']
                            );

                            $this->queue = $this->getQueueInstance($queueName);
                                                                                            __contruct()



                         public function addToQueue($item)
                         {
                             $this->client->putMessage($this->queue->name, serialize($item));
                         }


Saturday, July 9, 2011
PRIMEIRO QUE
 while (true){

         try{


                                                                      ENTRA, PRIMEIRO
                $this->logAction("Checking for messages...");

                //Read Queue


                                                                          QUE SAI
                $qMessage = $qManager->getMessage();

                //If no message, sleep for 3 seconds and try again
                if ($qMessage === null){
                    $this->logAction("No pending messages...");
                    sleep(3);
                    continue;
                }

                //Retrieve User
                {... doctrine query for stored twitter handle ...}

                //Clear Message
                $this->logAction("Removing message form queue...");
                $qManager->deleteMessage($qMessage);

                //Process User
                $this->processUser($user);

                //Warn User
                $this->sendWarning($user);

         } catch (Exception $e) {
             $this->logAction("Exception found:" .$e->getMessage

         }

         $this->logAction("Initiating sleep for next loop.");
         sleep(2);
  }
Saturday, July 9, 2011
PRIMEIRO QUE
 while (true){

         try{


                                                                      ENTRA, PRIMEIRO
                $this->logAction("Checking for messages...");

                //Read Queue


                                                                          QUE SAI
                $qMessage = $qManager->getMessage();

                //If no message, sleep for 3 seconds and try again
                if ($qMessage === null){
                    $this->logAction("No pending messages...");
                    sleep(3);
                    continue;
                }

                //Retrieve User
                {... doctrine query for stored twitter handle ...}

                //Clear Message
                $this->logAction("Removing message form queue...");
                $qManager->deleteMessage($qMessage);

                //Process User
                $this->processUser($user);

                //Warn User
                $this->sendWarning($user);

         } catch (Exception $e) {
             $this->logAction("Exception found:" .$e->getMessage

         }

         $this->logAction("Initiating sleep for next loop.");
         sleep(2);
  }
Saturday, July 9, 2011
PRIMEIRO QUE
 while (true){

         try{


                                                                       ENTRA, PRIMEIRO
                $this->logAction("Checking for messages...");

                //Read Queue


                                                                           QUE SAI
                $qMessage = $qManager->getMessage();

                //If no message, sleep for 3 seconds and try again
                if ($qMessage === null){
                    $this->logAction("No pending messages...");
                    sleep(3);
                    continue; function getMessage()
                        public
                }       {
                            $messages = $this->client->getMessages($this->queue->name, 1);
                //Retrieve User
                {... doctrine query for stored twitter handle ...}
                            if (count($messages) > 0){
                                $qMessage = array_shift($messages);
                //Clear Message
                $this->logAction("Removing= message form queue...");
                                $message     new stdClass();
                $qManager->deleteMessage($qMessage); = $qMessage;
                                $message->qMessage
                                $message->decoded = unserialize($qMessage->messagetext);
                //Process User
                $this->processUser($user);
                                return $message;
                            }
                //Warn User
                $this->sendWarning($user);
                            return null;
         } catch (Exception $e) {
                     }
             $this->logAction("Exception found:" .$e->getMessage

         }

         $this->logAction("Initiating sleep for next loop.");
         sleep(2);
  }
Saturday, July 9, 2011
PRIMEIRO QUE
 while (true){

         try{


                                                                       ENTRA, PRIMEIRO
                $this->logAction("Checking for messages...");

                //Read Queue


                                                                           QUE SAI
                $qMessage = $qManager->getMessage();

                //If no message, sleep for 3 seconds and try again
                if ($qMessage === null){
                    $this->logAction("No pending messages...");
                    sleep(3);
                    continue; function getMessage()
                        public
                }       {
                            $messages = $this->client->getMessages($this->queue->name, 1);
                //Retrieve User
                {... doctrine query for stored twitter handle ...}
                            if (count($messages) > 0){
                                $qMessage = array_shift($messages);
                //Clear Message
                $this->logAction("Removing= message form queue...");
                                $message     new stdClass();
                $qManager->deleteMessage($qMessage); = $qMessage;
                                $message->qMessage
                                $message->decoded = unserialize($qMessage->messagetext);
                //Process User
                $this->processUser($user);
                                return $message;
                            }
                //Warn User
                $this->sendWarning($user);             array(
                            return null;                       'messageid'         =>   $messageId,
                                                               'insertiontime'     =>   $insertionTime,
         } catch (Exception $e) {
                     }                                         'expirationtime'    =>   $expirationTime,
             $this->logAction("Exception found:" .$e->getMessage
                                                               'popreceipt'        =>   $popReceipt,
                                                               'timenextvisible'   =>   $timeNextVisible,
         }
                                                               'dequeuecount'      =>   $dequeueCount,
                                                               'messagetext'       =>   $messageText
         $this->logAction("Initiating sleep for next loop.");
                                                           );
         sleep(2);
  }
Saturday, July 9, 2011
PRIMEIRO QUE
 while (true){

         try{


                                                                      ENTRA, PRIMEIRO
                $this->logAction("Checking for messages...");

                //Read Queue


                                                                          QUE SAI
                $qMessage = $qManager->getMessage();

                //If no message, sleep for 3 seconds and try again
                if ($qMessage === null){
                    $this->logAction("No pending messages...");
                    sleep(3);
                    continue;
                }

                //Retrieve User
                {... doctrine query for stored twitter handle ...}

                //Clear Message
                $this->logAction("Removing message form queue...");
                $qManager->deleteMessage($qMessage);

                //Process User
                $this->processUser($user);

                //Warn User
                $this->sendWarning($user);

         } catch (Exception $e) {
             $this->logAction("Exception found:" .$e->getMessage

         }

         $this->logAction("Initiating sleep for next loop.");
         sleep(2);
  }
Saturday, July 9, 2011
PRIMEIRO QUE
 while (true){

         try{


                                                                      ENTRA, PRIMEIRO
                $this->logAction("Checking for messages...");

                //Read Queue


                                                                          QUE SAI
                $qMessage = $qManager->getMessage();

                //If no message, sleep for 3 seconds and try again
                if ($qMessage === null){
                    $this->logAction("No pending messages...");
                    sleep(3);
                    continue;
                }

                //Retrieve User
                {... doctrine query for stored twitter handle ...}

                //Clear Message
                $this->logAction("Removing message form queue...");
                $qManager->deleteMessage($qMessage);            Após 20 segundos, a mensagem
                //Process User                                         volta para a fila
                $this->processUser($user);

                //Warn User
                $this->sendWarning($user);

         } catch (Exception $e) {
             $this->logAction("Exception found:" .$e->getMessage

         }

         $this->logAction("Initiating sleep for next loop.");
         sleep(2);
  }
Saturday, July 9, 2011
SAINDO PELA JANELA


    • Veja todas mudanças: github.com/rdohms/Sample-Azure-
        App

    • Compare             estes branches:

              non-cloud-version x cloud-designed-version



Saturday, July 9, 2011
FECHANDO A JANELA


    • Descobrimos              o que é a nuvem

    • Vimos              razões por que escolher a nuvem

    • Conhecemos               o Windows Azure e seus recursos

    • Olhamos              rapidamente em como isso afeta nosso código



Saturday, July 9, 2011
LEITURA COMPLEMENTAR...


        PHP Development in the
        Cloud

        ISBN: 9780981034522
        Pages: 172
        Authors: Ivo Jansch and Vito Chin

               http://bit.ly/i9Awk0



Saturday, July 9, 2011
COMECE A BRINCAR..
    • Conta              de teste gratuita: WindowsAzurePass.com

    • Procure               o pessoal da Microsoft no evento


                                         http://azurephp.com
                                   http://phpazure.codeplex.com/
                                http://azurephptools.codeplex.com/
                            http://www.ben-waine.co.uk/blog/php-azure
                         http://marvelley.com/category/php/php-on-azure/


Saturday, July 9, 2011
http://slides.doh.ms
 twitter.com/rdohms
 http://doh.ms


                         Perguntas?
                         OBRIGADO!
                         rafael@doh.ms



         Avalie essa palestra: http://joind.in/3572
Saturday, July 9, 2011

Más contenido relacionado

Más de Rafael Dohms

The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024Rafael Dohms
 
Application Metrics - IPC2023
Application Metrics - IPC2023Application Metrics - IPC2023
Application Metrics - IPC2023Rafael Dohms
 
How'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsHow'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsRafael Dohms
 
Architectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRArchitectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRRafael Dohms
 
Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Rafael Dohms
 
Application metrics - Confoo 2019
Application metrics - Confoo 2019Application metrics - Confoo 2019
Application metrics - Confoo 2019Rafael Dohms
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Rafael Dohms
 
Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Rafael Dohms
 
Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...Rafael Dohms
 
Composer The Right Way - 010PHP
Composer The Right Way - 010PHPComposer The Right Way - 010PHP
Composer The Right Way - 010PHPRafael Dohms
 
Writing Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtWriting Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtRafael Dohms
 
Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16Rafael Dohms
 
Composer the Right Way - MM16NL
Composer the Right Way - MM16NLComposer the Right Way - MM16NL
Composer the Right Way - MM16NLRafael Dohms
 
Composer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNComposer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNRafael Dohms
 
Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.Rafael Dohms
 
A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015Rafael Dohms
 

Más de Rafael Dohms (20)

The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024
 
Application Metrics - IPC2023
Application Metrics - IPC2023Application Metrics - IPC2023
Application Metrics - IPC2023
 
How'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsHow'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision Records
 
Architectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRArchitectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBR
 
Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)
 
Application metrics - Confoo 2019
Application metrics - Confoo 2019Application metrics - Confoo 2019
Application metrics - Confoo 2019
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18
 
Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18
 
Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
 
Composer The Right Way - 010PHP
Composer The Right Way - 010PHPComposer The Right Way - 010PHP
Composer The Right Way - 010PHP
 
Writing Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtWriting Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, Utrecht
 
Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
 
Composer the Right Way - MM16NL
Composer the Right Way - MM16NLComposer the Right Way - MM16NL
Composer the Right Way - MM16NL
 
Composer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNComposer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRN
 
Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.
 
A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015
 

TDC 2011 - Open a Window, see the clouds

  • 1. Open a Window, see the clouds Rafael Dohms photo credit: Denis Grzetic Saturday, July 9, 2011
  • 2. Rafael Dohms photo credit: Eli White Evangelista PHP, membro ativo da Comunidade PHP e certificado ZCE. Ele ajudou na fundação de dois Grupos de Usuários de PHP ao longo do tempo e hoje compartilha a coordenação do PHPSP. Desenvolvedor, gamer e apaixonado por código ele também é host do primeiro podcast de PHP do Brasil: PHPSPCast. Atualmente ele trabalha na equipe SWAT do grupo MIH, uma equipe de experts que fornecem conhecimento técnico para o grupo além de trabalhar com P&D buscando novos nichos da internet e tecnologia. Seu papel como Desenvolvedor Sênior é codar, treinar e auxiliar outras empresas e se divertir enquanto faz isso. Saturday, July 9, 2011
  • 3. OLHANDO PELA JANELA •O que é a nuvem? • Por que escolher a nuvem? • Vamos conhecer o Windows Azure • Como isso vai afetar meu código? Saturday, July 9, 2011
  • 4. O QUE É A NUVEM? não é só mais uma palavra no buzzword bingo Saturday, July 9, 2011
  • 5. HOSPEDAGEM COMUM • Conta compatilhada, VPS ou máquina local • Uma máquina, um local • Pagamento mensal Saturday, July 9, 2011
  • 6. Própria HOSPEDAGEM COMUM • Conta compatilhada, VPS ou máquina local • Uma máquina, um local • Pagamento mensal Saturday, July 9, 2011
  • 7. COMPUTAÇÃO NA NUVEM • Menos “apego físico” (virtualização) • Uma ou mais máquinas ou “instancias” • Geograficamente espalhada • Pagamento por hora/recurso • “abstração” de recursos • 3 Sabores: IaaS, PaaS, SaaS Saturday, July 9, 2011
  • 8. Dados Aplicação Software Sistema Operacional Hardware/Rede Saturday, July 9, 2011
  • 9. Armazenamento Dados Compartilhar Publicação Aplicação Desenvolvimento MySQL Software Apache Configuração Sistema Operacional Upgrades Resfriamento Hardware/Rede Cabeamento Saturday, July 9, 2011
  • 10. IaaS a Service” “Infrastructure as “Infraestrutura como Serviço” Dados Aplicação Software Sistema Operacional Hardware/Rede Saturday, July 9, 2011
  • 11. IaaS a Service” “Infrastructure as “Infraestrutura como Serviço” Dados Aplicação Software Sistema Operacional você eles Hardware/Rede Saturday, July 9, 2011
  • 12. PaaS “Platform as a Service” “Plataforma como Serviço” Dados Aplicação Software Sistema Operacional Hardware/Rede Saturday, July 9, 2011
  • 13. PaaS “Platform as a Service” “Plataforma como Serviço” Dados Aplicação você eles Software Sistema Operacional Hardware/Rede Saturday, July 9, 2011
  • 14. SaaS “Software as a Service” “Software como Serviço” Dados Aplicação Software Sistema Operacional Hardware/Rede Saturday, July 9, 2011
  • 15. SaaS “Software as a Service” “Software como Serviço” Dados você eles Aplicação Software Sistema Operacional Hardware/Rede Saturday, July 9, 2011
  • 16. X POR QUE ESCOLHER A NUVEM? Quais são as vantagens de escolher a nuvem? Saturday, July 9, 2011
  • 17. trafego tempo O MODELO CONTA DE LUZ Saturday, July 9, 2011
  • 18. trafego tempo O MODELO CONTA DE LUZ Saturday, July 9, 2011
  • 19. trafego pico tempo O MODELO CONTA DE LUZ Saturday, July 9, 2011
  • 20. trafego pico tempo O MODELO CONTA DE LUZ Saturday, July 9, 2011
  • 21. trafego pico tempo O MODELO CONTA DE LUZ Saturday, July 9, 2011
  • 22. IaaS Paas SaaS custos gerenciamento do servidor gerenciamento do software publicação da aplicação Saturday, July 9, 2011
  • 26. ESCALABILIDADE Computação sem estado + Armazenamento durável Saturday, July 9, 2011
  • 27. ESCALABILIDADE Computação sem estado + Armazenamento durável Saturday, July 9, 2011
  • 29. Windows Azure Fabric Compute Storage Saturday, July 9, 2011
  • 30. Fabric Middleware, usado para desenvolver, testar, publicar e gerenciar sua aplicação. AppFabric developer Saturday, July 9, 2011
  • 31. Fabric Compute Storage Saturday, July 9, 2011
  • 32. Compute Web Role Worker Role VM Role Máquina virtual de Aplicação Web Processamento em Windows Server rodando sobre o plano de fundo 2008 carregada IIS sob demanda Saturday, July 9, 2011
  • 33. Fabric Compute Storage Saturday, July 9, 2011
  • 34. Versão cacheada de CDN qualquer recurso com uma URI Storage Armazenamento de dados Table Storage Blob Storage SQL Azure Queue Troca de Armazenamento Texto e dados Compatível com o mensagens entre o estruturado binários SQL Server Web e o Worker Saturday, July 9, 2011
  • 35. PRONTO PRA RODAR para Desenvolver e Publicar • Requisitos: • IIS7 e ferramentas • Azure SDK (instala o DevAppFabric, o simulador de azure) • Command Line Tools (linha de comando) • Command line tools for PHP Saturday, July 9, 2011
  • 36. CAIXA DE FERRAMENTAS • Command Line tools for PHP • Cria o pacote da aplicação e roda no emulador, simulando o computacional e o armazenamento. • Azure Tools para Eclipse • Torna a maioria dos processos “next, next finish” e fornece uma IDE completa. Saturday, July 9, 2011
  • 37. Ambiente do Desenvolvedor Simulador Azure Código (Dev fabric) Ferramentas de empacotamento (linha de comando ou eclipse) Pacote + Configuração do Serviço Azure Window Azure (AppFabric) SQLAzure Storage Saturday, July 9, 2011
  • 38. Ambiente do Desenvolvedor Simulador Azure Código (Dev fabric) PHP Ferramentas de empacotamento (linha de comando ou eclipse) Pacote + Configuração do Serviço Azure Window Azure (AppFabric) SQLAzure Storage Saturday, July 9, 2011
  • 39. Ambiente do Desenvolvedor Simulador Azure Código (Dev fabric) PHP Ferramentas de empacotamento (linha de comando ou eclipse) Pacote + Configuração do Serviço Azure Window Azure (AppFabric) SQLAzure Storage Saturday, July 9, 2011
  • 40. Ambiente do Desenvolvedor Simulador Azure Código (Dev fabric) php package.php PHP --project="twitter-azure" Ferramentas de empacotamento --target="c:azure-build" de comando ou eclipse) (linha --source="C:twitter-azure" Pacote + Configuração do Serviço --defaultDoc="public/index.php" --phpRuntime="C:Program Files (x86)PHPv5.3" --cleanRebuild --runDevFabric Azure Window Azure (AppFabric) SQLAzure Storage Saturday, July 9, 2011
  • 41. Ambiente do Desenvolvedor Simulador Azure Código (Dev fabric) PHP Ferramentas de empacotamento (linha de comando ou eclipse) Pacote + Configuração do Serviço Azure Window Azure (AppFabric) SQLAzure Storage Saturday, July 9, 2011
  • 42. O BOM • APIs em REST • Armazenamento • Diagnósticos • BD Relacional: SQL Azure • Arquitetura por “Roles” Saturday, July 9, 2011
  • 43. O RUIM • Gerenciamento apenas pelo Windows • Sem Emulador Azure para SO não-Windows • Sem ferramentas de empacotamento para SO não-Windows Saturday, July 9, 2011
  • 44. COMO ISSO AFETA MEU CÓDIGO? Que ferramentas podemos usar e como devemos desenhar nossas aplicações? Saturday, July 9, 2011
  • 45. COM O QUE DEVO ME PREOCUPAR? Saturday, July 9, 2011
  • 46. COM O QUE DEVO ME PREOCUPAR? Código Saturday, July 9, 2011
  • 47. COM O QUE DEVO ME PREOCUPAR? Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 48. COM O QUE DEVO ME PREOCUPAR? Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 49. COM O QUE DEVO ME PREOCUPAR? Escalando a aplicação Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 50. COM O QUE DEVO ME PREOCUPAR? Escalando a Sem Armazenamento aplicação Local Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 51. COM O QUE DEVO ME PREOCUPAR? Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 52. COM O QUE DEVO ME PREOCUPAR? Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Worker Roles Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 53. COM O QUE DEVO ME PREOCUPAR? Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Worker Roles Filas Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 54. COM O QUE DEVO ME PREOCUPAR? Armazenamento Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Worker Roles Filas Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 55. COM O QUE DEVO ME PREOCUPAR? Que tipo? Armazenamento Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Worker Roles Filas Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 56. COM O QUE DEVO ME PREOCUPAR? Tabela / Blob Que tipo? Armazenamento Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Worker Roles Filas Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 57. COM O QUE DEVO ME PREOCUPAR? Tabela / Blob Framework ou PHP SDK Que tipo? Armazenamento Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Worker Roles Filas Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 58. COM O QUE DEVO ME PREOCUPAR? Tabela / Blob Framework ou PHP SDK Que tipo? Banco de Dados Armazenamento Relacional Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Worker Roles Filas Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 59. COM O QUE DEVO ME PREOCUPAR? Tabela / Blob Framework ou PHP SDK Que tipo? Banco de Migrar para SQL Azure Dados Armazenamento Relacional Escalando a Sem Armazenamento Compartilhamento Local de sessão aplicação Worker Roles Filas Arquitetura Código PHP rodando no IIS/Windows Saturday, July 9, 2011
  • 60. FRAMEWORKS PRONTOS PARA O AZURE Saturday, July 9, 2011
  • 61. O QUE FAZ ELE SER COMPATÍVEL? Código Roda usando PHP no Windows? Ferramentas Tem wrappers das APIs? Banco de Dados É compatível com MS SQL Server? Saturday, July 9, 2011
  • 62. Ferramentas • Blobs, Tables e Queues (operações CRUD) • Classes auxiliares para transporte HTTP, AuthN/ AuthZ, REST and Gerenciamento de Erros • Gerenciamento, Instrumentação e supporte a logs Banco de Dados • Não testado, mas deve funcionar. Saturday, July 9, 2011
  • 63. Banco de Dados • Drivers de MS-SQL* são compatíveis com SQLAzure * Usando pdo_sql_server, possivelmente o pdo_dblib Powered by Doctrine: Saturday, July 9, 2011
  • 64. • PHP roda normalmente no Azure, qualquer framework vai funcionar. • Outras ferramentas para se comunicar com recursos como: BD, Filas etc... • Estes aqui já foram testados! Saturday, July 9, 2011
  • 65. AZURE PHP SDK • Serviços: • Blob Storage • Table Storage • Queue Storage • Diagnostic Tools • Compatível com PHP 5+ Saturday, July 9, 2011
  • 66. SAINDO PELA JANELA Aplicação de teste para ilustrar • Aplicação de teste: “Twitter RT Calculator” • Objetivo: Analisar sues últimos tweets, verificar quais foram re-tuitados e fazer cálculos baseado em palavras e localizações. • Exemplificar a migração: • Banco de dados: MySQL > SQLAzure • Mover o processamento para um Worker Role e usar a Fila Saturday, July 9, 2011
  • 67. SAINDO PELA JANELA Aplicação de teste para ilustrar • Aplicação de teste: “Twitter RT Calculator” • Objetivo: Analisar sues últimos tweets, verificar quais foram re-tuitados e fazer cálculos baseado em palavras e localizações. • Exemplificar a migração: • Banco de dados: MySQL > SQLAzure • Mover o processamento para um Worker Role e usar a Fila Saturday, July 9, 2011
  • 68. Twitter OAuth Segura ai.. Saturday, July 9, 2011
  • 69. Twitter OAuth Segura ai.. Saturday, July 9, 2011
  • 70. Twitter OAuth Segura ai.. Saturday, July 9, 2011
  • 71. Twitter OAuth Segura ai.. MySQL Saturday, July 9, 2011
  • 72. Twitter OAuth Segura ai.. MySQL Resultados Saturday, July 9, 2011
  • 73. Twitter OAuth Segura ai.. MySQL Resultados Saturday, July 9, 2011
  • 74. Twitter OAuth Segura ai.. MySQL Resultados Saturday, July 9, 2011
  • 75. Twitter OAuth Te ligo mais tarde.. Saturday, July 9, 2011
  • 76. Twitter OAuth Queue Te ligo mais tarde.. Saturday, July 9, 2011
  • 77. Twitter OAuth Queue Te ligo mais tarde.. Worker Saturday, July 9, 2011
  • 78. Twitter OAuth Queue Te ligo mais tarde.. Worker Saturday, July 9, 2011
  • 79. Twitter OAuth Queue Te ligo mais tarde.. Worker Saturday, July 9, 2011
  • 80. Twitter OAuth Queue Te ligo mais tarde.. Worker SQLAzure Saturday, July 9, 2011
  • 81. Twitter OAuth Queue Te ligo mais tarde.. Worker SQLAzure Saturday, July 9, 2011
  • 82. Twitter OAuth Queue Te ligo mais tarde.. Worker Resultados SQLAzure Saturday, July 9, 2011
  • 83. Twitter OAuth Queue Te ligo mais tarde.. Worker Worker Worker Worker Worker Worker Worker Worker Worker Worker Worker Resultados SQLAzure Saturday, July 9, 2011
  • 84. USANDO SQLAZURE PDO MSSQL Driver doctrine.dbal.connection_options: driver: pdo_sqlsrv dbname: twitter-sample-app host: pl69qjwy8k.database.windows.net port: 1433 user: rdohmsDemo@pl69qjwy8k password: *password* Saturday, July 9, 2011
  • 85. TODOS PARA A FILA //Add user to our Queue $qItem = new stdClass(); $qItem->twitter_handle = $twitterInfo->screen_name; $qManager = new AzureQueue($this->getApp()->getConfig('azure')); $qManager->addToQueue($qItem); Saturday, July 9, 2011
  • 86. TODOS PARA A FILA //Add user to our Queue $qItem = new stdClass(); $qItem->twitter_handle = $twitterInfo->screen_name; $qManager = new AzureQueue($this->getApp()->getConfig('azure')); $qManager->addToQueue($qItem); $this->client = new Zend_Service_WindowsAzure_Storage_Queue( $qConfig['host'], $qConfig['accountName'], $qConfig['accountKey'] ); $this->queue = $this->getQueueInstance($queueName); __contruct() Saturday, July 9, 2011
  • 87. TODOS PARA A FILA //Add user to our Queue $qItem = new stdClass(); $qItem->twitter_handle = $twitterInfo->screen_name; $qManager = new AzureQueue($this->getApp()->getConfig('azure')); $qManager->addToQueue($qItem); $this->client = new Zend_Service_WindowsAzure_Storage_Queue( $qConfig['host'], $qConfig['accountName'], $qConfig['accountKey'] ); $this->queue = $this->getQueueInstance($queueName); __contruct() public function addToQueue($item) { $this->client->putMessage($this->queue->name, serialize($item)); } Saturday, July 9, 2011
  • 88. PRIMEIRO QUE while (true){ try{ ENTRA, PRIMEIRO $this->logAction("Checking for messages..."); //Read Queue QUE SAI $qMessage = $qManager->getMessage(); //If no message, sleep for 3 seconds and try again if ($qMessage === null){ $this->logAction("No pending messages..."); sleep(3); continue; } //Retrieve User {... doctrine query for stored twitter handle ...} //Clear Message $this->logAction("Removing message form queue..."); $qManager->deleteMessage($qMessage); //Process User $this->processUser($user); //Warn User $this->sendWarning($user); } catch (Exception $e) { $this->logAction("Exception found:" .$e->getMessage } $this->logAction("Initiating sleep for next loop."); sleep(2); } Saturday, July 9, 2011
  • 89. PRIMEIRO QUE while (true){ try{ ENTRA, PRIMEIRO $this->logAction("Checking for messages..."); //Read Queue QUE SAI $qMessage = $qManager->getMessage(); //If no message, sleep for 3 seconds and try again if ($qMessage === null){ $this->logAction("No pending messages..."); sleep(3); continue; } //Retrieve User {... doctrine query for stored twitter handle ...} //Clear Message $this->logAction("Removing message form queue..."); $qManager->deleteMessage($qMessage); //Process User $this->processUser($user); //Warn User $this->sendWarning($user); } catch (Exception $e) { $this->logAction("Exception found:" .$e->getMessage } $this->logAction("Initiating sleep for next loop."); sleep(2); } Saturday, July 9, 2011
  • 90. PRIMEIRO QUE while (true){ try{ ENTRA, PRIMEIRO $this->logAction("Checking for messages..."); //Read Queue QUE SAI $qMessage = $qManager->getMessage(); //If no message, sleep for 3 seconds and try again if ($qMessage === null){ $this->logAction("No pending messages..."); sleep(3); continue; function getMessage() public } { $messages = $this->client->getMessages($this->queue->name, 1); //Retrieve User {... doctrine query for stored twitter handle ...} if (count($messages) > 0){ $qMessage = array_shift($messages); //Clear Message $this->logAction("Removing= message form queue..."); $message new stdClass(); $qManager->deleteMessage($qMessage); = $qMessage; $message->qMessage $message->decoded = unserialize($qMessage->messagetext); //Process User $this->processUser($user); return $message; } //Warn User $this->sendWarning($user); return null; } catch (Exception $e) { } $this->logAction("Exception found:" .$e->getMessage } $this->logAction("Initiating sleep for next loop."); sleep(2); } Saturday, July 9, 2011
  • 91. PRIMEIRO QUE while (true){ try{ ENTRA, PRIMEIRO $this->logAction("Checking for messages..."); //Read Queue QUE SAI $qMessage = $qManager->getMessage(); //If no message, sleep for 3 seconds and try again if ($qMessage === null){ $this->logAction("No pending messages..."); sleep(3); continue; function getMessage() public } { $messages = $this->client->getMessages($this->queue->name, 1); //Retrieve User {... doctrine query for stored twitter handle ...} if (count($messages) > 0){ $qMessage = array_shift($messages); //Clear Message $this->logAction("Removing= message form queue..."); $message new stdClass(); $qManager->deleteMessage($qMessage); = $qMessage; $message->qMessage $message->decoded = unserialize($qMessage->messagetext); //Process User $this->processUser($user); return $message; } //Warn User $this->sendWarning($user); array( return null; 'messageid' => $messageId, 'insertiontime' => $insertionTime, } catch (Exception $e) { } 'expirationtime' => $expirationTime, $this->logAction("Exception found:" .$e->getMessage 'popreceipt' => $popReceipt, 'timenextvisible' => $timeNextVisible, } 'dequeuecount' => $dequeueCount, 'messagetext' => $messageText $this->logAction("Initiating sleep for next loop."); ); sleep(2); } Saturday, July 9, 2011
  • 92. PRIMEIRO QUE while (true){ try{ ENTRA, PRIMEIRO $this->logAction("Checking for messages..."); //Read Queue QUE SAI $qMessage = $qManager->getMessage(); //If no message, sleep for 3 seconds and try again if ($qMessage === null){ $this->logAction("No pending messages..."); sleep(3); continue; } //Retrieve User {... doctrine query for stored twitter handle ...} //Clear Message $this->logAction("Removing message form queue..."); $qManager->deleteMessage($qMessage); //Process User $this->processUser($user); //Warn User $this->sendWarning($user); } catch (Exception $e) { $this->logAction("Exception found:" .$e->getMessage } $this->logAction("Initiating sleep for next loop."); sleep(2); } Saturday, July 9, 2011
  • 93. PRIMEIRO QUE while (true){ try{ ENTRA, PRIMEIRO $this->logAction("Checking for messages..."); //Read Queue QUE SAI $qMessage = $qManager->getMessage(); //If no message, sleep for 3 seconds and try again if ($qMessage === null){ $this->logAction("No pending messages..."); sleep(3); continue; } //Retrieve User {... doctrine query for stored twitter handle ...} //Clear Message $this->logAction("Removing message form queue..."); $qManager->deleteMessage($qMessage); Após 20 segundos, a mensagem //Process User volta para a fila $this->processUser($user); //Warn User $this->sendWarning($user); } catch (Exception $e) { $this->logAction("Exception found:" .$e->getMessage } $this->logAction("Initiating sleep for next loop."); sleep(2); } Saturday, July 9, 2011
  • 94. SAINDO PELA JANELA • Veja todas mudanças: github.com/rdohms/Sample-Azure- App • Compare estes branches: non-cloud-version x cloud-designed-version Saturday, July 9, 2011
  • 95. FECHANDO A JANELA • Descobrimos o que é a nuvem • Vimos razões por que escolher a nuvem • Conhecemos o Windows Azure e seus recursos • Olhamos rapidamente em como isso afeta nosso código Saturday, July 9, 2011
  • 96. LEITURA COMPLEMENTAR... PHP Development in the Cloud ISBN: 9780981034522 Pages: 172 Authors: Ivo Jansch and Vito Chin http://bit.ly/i9Awk0 Saturday, July 9, 2011
  • 97. COMECE A BRINCAR.. • Conta de teste gratuita: WindowsAzurePass.com • Procure o pessoal da Microsoft no evento http://azurephp.com http://phpazure.codeplex.com/ http://azurephptools.codeplex.com/ http://www.ben-waine.co.uk/blog/php-azure http://marvelley.com/category/php/php-on-azure/ Saturday, July 9, 2011
  • 98. http://slides.doh.ms twitter.com/rdohms http://doh.ms Perguntas? OBRIGADO! rafael@doh.ms Avalie essa palestra: http://joind.in/3572 Saturday, July 9, 2011