SlideShare ist ein Scribd-Unternehmen logo
1 von 58
Downloaden Sie, um offline zu lesen
e r                   3         e r
                s w                    /2
                                          2
                                          5        arb
           a n                    i ew        ian
                                                  b

       h e                al k /v           @
     t             r n/ t
                 e .i m il.c           o m
is             rb nd .co a
             a oi ir m
            B /j p g
          n p:/ /ph er@
       Ia tt :/ rb
          h ttp a
           h n.b
             ia
“0MQ is
unbelievably cool
– if you haven’t
got a project that
needs it, make
one up”
jon gifford - loggly
queue        esb


pipeline    async



pub/sub    gateway
request/response

$ctx = new ZMQContext();       rep.php
$server =
  new ZMQSocket($ctx, ZMQ::SOCKET_REP);
$server->bind("tcp://*:5454");

while(true) {
  $message = $server->recv();
  $server->send($message . " World");
}
request/response

$ctx = new ZMQContext();      req.php
$req =
  new ZMQSocket($ctx, ZMQ::SOCKET_REQ);
$req->connect("tcp://localhost:5454");

$req->send("Hello");
echo $req->recv();
import zmq                   rep.py
context = zmq.Context()
server = context.socket(zmq.REP)
server.connect("tcp://localhost:5455")

while True:
    message = server.recv()
    print "Sending", message, "Worldn"
    server.send(message + " World")
Image: http://flickr.com/photos/sebastian_bergmann/3318754086
wget http://download.zeromq.org/
zeromq-2.1.1.tar.gz
tar xvzf zeromq-2.1.1.tar.gz
cd zeromq-2.1.1/
./configure
make
sudo make install

pear channel-discover pear.zero.mq
pecl install zero.mq/zmq-beta
echo "extension=zmq.so" > 
                    /etc/php.d/zmq.ini

http://github.com/zeromq/zeromq2
atomic   string   multipart



messaging
Post Office Image: http://www.flickr.com/photos/10804218@N00/4315282973
        Post Box Image: http://www.flickr.com/photos/kenjonbro/3027166169
queue
queue
$ctx   = new ZMQContext();
$front = $ctx->getSocket(ZMQ::SOCKET_XREP);
$back = $ctx->getSocket(ZMQ::SOCKET_XREQ);
$front->bind('tcp://*:5454');
$back->bind ('tcp://*:5455');

$poll = new ZMQPoll();
$poll->add($front, ZMQ::POLL_IN);
$poll->add($back, ZMQ::POLL_IN);
$read = $write = array();
$snd   = ZMQ::MODE_SNDMORE;
$rcv   = ZMQ::SOCKOPT_RCVMORE;
                                    queu e.php
while(true) {
 $events = $poll->poll($read, $write);
 foreach($read as $socket) {
  if($socket === $front) {
    do {
     $msg = $front->recv();
     $more = $front->getSockOpt($rcv);
     $back->send($msg, $more ? $snd:0);
    } while($more);
  } else if($socket === $back) {
    do {
     $msg = $back->recv();
     $more = $back->getSockOpt($rcv);
     $front->send($msg, $more ? $snd:0);
    } while($more);
}}}
0MQ1      0MQ2

Socket                    STDIN

            POLL




            events
$ctx = new ZMQContext();
$sock = $ctx->getSocket(ZMQ::SOCKET_PULL);
$sock->bind("tcp://*:5555");
$fh = fopen("php://stdin", 'r');

$poll = new ZMQPoll();
$poll->add($sock, ZMQ::POLL_IN);
$poll->add($fh, ZMQ::POLL_IN);

while(true) {
  $events = $poll->poll($read, $write);
  if($read[0] === $sock) {
    echo "ZMQ: ", $read[0]->recv();
  } else {
    echo "STDIN: ", fgets($read[0]);
}}
                                   poll.php
stable / unstable




  Image: http://www.flickr.com/photos/pelican/235461339/
pipeline
pipeline
define("NUM_WORKERS", 10);
for($i = 0; $i < NUM_WORKERS; $i++) {
  if(pcntl_fork() == 0) {
    `php work.php`; exit;
  }
}                          con troller.php
$ctx = new ZMQContext();
$work = $ctx->getSocket(ZMQ::SOCKET_PUSH);
$ctrl = $ctx->getSocket(ZMQ::SOCKET_PUSH);
$work->setSockOpt(ZMQ::SOCKOPT_HWM, 10);
$ctrl->setSockOpt(ZMQ::SOCKOPT_HWM, 1);
$work->bind("ipc:///tmp/work");
$ctrl->bind("ipc:///tmp/control");
sleep(1);

$fh = fopen('data.txt', 'r');

while($data = fgets($fh)) {
  $work->send($data);
}

for($i = 0; $i < NUM_WORKERS+1; $i++) {
  $ctrl->send("END");
}
work.php
$ctx = new ZMQContext();
$work = $ctx->getSocket(ZMQ::SOCKET_PULL);
$work->setSockOpt(ZMQ::SOCKOPT_HWM, 1);
$work->connect("ipc:///tmp/work");
$sink = $ctx->getSocket(ZMQ::SOCKET_PUSH);
$sink->connect("ipc:///tmp/results");
$ctrl = $ctx->getSocket(ZMQ::SOCKET_PULL);
$ctrl->setSockOpt(ZMQ::SOCKOPT_HWM, 1);
$ctrl->connect("ipc:///tmp/control");

$poll = new ZMQPoll();
$poll->add($work, ZMQ::POLL_IN);
$read = $write = array();
while(true) {
  $ev = $poll->poll($read, $write, 5000);
  if($ev) {
    $message = $work->recv();
    $sink->send(strlen($message));
  } else {
    try {
      if($ctrl->recv(ZMQ::MODE_NOBLOCK)) {
         exit();
      }
    } catch(ZMQException $e) {
        // noop
    }
  }
}
sink.php
$ctx = new ZMQContext();

$res = $ctx->getSocket(ZMQ::SOCKET_PULL);
$res->bind("ipc:///tmp/results");

$ctrl = $ctx->getSocket(ZMQ::SOCKET_PULL);
$ctrl->setSockOpt(ZMQ::SOCKOPT_HWM, 1);
$ctrl->connect("ipc:///tmp/control");

$poll = new ZMQPoll();
$poll->add($res, ZMQ::POLL_IN);

$read = $write = array();
$total = 0;
while(true) {
  $ev = $poll->poll($read, $write, 10000);
  if($ev) {
    $total += $res->recv();
  } else {
    try {
      if($ctrl->recv(ZMQ::MODE_NOBLOCK)) {
        echo $total, PHP_EOL;
        exit();
      }
    } catch (ZMQException $e) {
      //noop
    }
  }
}
$ php controller.php   $ php sink.php
Starting Worker 0      39694
Starting Worker 1
Starting Worker 2
Starting Worker 3
Starting Worker 4
Starting Worker 5
Starting Worker 6
Starting Worker 7
Starting Worker 8
Starting Worker 9
filter chain
im age up loaded
 for proc essing
re-encoding
  scale out
resizing and
  quan tizing
fan-in for
validation
watermark
pub/sub




  Image: http://www.flickr.com/photos/nikonvscanon/4519133003/
pub/sub
pub             send
                “h

         “hi”
                  i”
  i”
 “h


sub      sub           sub




                              i”
                              “h
ted      ann           ned
pub/sub

$ctx = new ZMQContext();
$pub = $ctx->getSocket(ZMQ::SOCKET_PUB);
$pub->bind('tcp://*:5566');
$pull = $ctx->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://*:5567');

while(true) {
    $message = $pull->recv();
    $pub->send($message);
}                               server.php
$name = htmlspecialchars($_POST['name']);
$msg =htmlspecialchars($_POST['message']);

$ctx = new ZMQContext();
$send = $ctx->getSocket(ZMQ::SOCKET_PUSH);
$send->connect('tcp://localhost:5567');

if($msg == 'm:joined') {
  $send->send(
     "<em>" . $name . " has joined</em>");
} else {
  $send->send($name . ': ' . $msg);
}

                            send.php
$ctx = new ZMQContext();
$sub = $ctx->getSocket(ZMQ::SOCKET_SUB);
$sub->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE,'');
$sub->connect('tcp://localhost:5566');
$poll = new ZMQPoll();
$poll->add($sub, ZMQ::POLL_IN);
$read = $wri = array();
while(true) {
  $ev = $poll->poll($read, $wri, 5000000);
  if($ev > 0) {
    echo "<script type='text/javascript'>
                     parent.updateChat('";
    echo $sub->recv() ."');</script>";
  }
  ob_flush();
  flush();
}                                ch at.php
sub          sub
 user         data



pub     pub    pub

web     web    web
$ctx = new ZMQContext();
$socket = $ctx->getSocket(ZMQ::SOCKET_PUB);
$socket->connect("ipc:///tmp/usercache");
$socket->connect("ipc:///tmp/datacache");
$type = array('users', 'data');

while(true) {
  $socket->send($type[array_rand($type)],
                         ZMQ::MODE_SNDMORE);
  $socket->send(rand(0, 12));
  sleep(rand(0,3));
}                              cach e.php
$ctx = new ZMQContext();
$socket = $ctx->getSocket(ZMQ::SOCKET_SUB);
$socket->setSockOpt(
          ZMQ::SOCKOPT_SUBSCRIBE, "users");
$socket->bind("ipc:///tmp/usercache");

while(true) {
    $cache = $socket->recv();
    $request = $socket->recv();
    echo "Clearing $cache $requestn";
}


                     userlistener.php
types of transport

     inproc         ipc




   tcp        pgm
distro   sub   web
client
                   sub   web
         sub

event
         sub       sub   web
 pub

          distro   sub   web
client
         sub       db
$ctx = new ZMQContext();
$out = $ctx->getSocket(ZMQ::SOCKET_PUB);
$out->setSockOpt(ZMQ::SOCKOPT_RATE, 10000);
$out->connect("epgm://;239.192.0.1:7601");

$in = $ctx->getSocket(ZMQ::SOCKET_PULL);
$in->bind("tcp://*:6767");

$device = new ZMQDevice(
         ZMQ::DEVICE_FORWARDER, $in, $out);



                      eventhub.php
$ctx = new ZMQContext();
$in = $ctx->getSocket(ZMQ::SOCKET_SUB);
$in->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, '');
$in->setSockOpt(ZMQ::SOCKOPT_RATE, 10000);
$in->connect("epgm://;239.192.0.1:7601");
$out = $ctx->getSocket(ZMQ::SOCKET_PUB);
$out->bind("ipc:///tmp/events");

$device = new ZMQDevice(
         ZMQ::DEVICE_FORWARDER, $in, $out);



                        distro.php
$ctx = new ZMQContext();
$in = $ctx->getSocket(ZMQ::SOCKET_SUB);
for($i = 0; $i<100; $i++) {
   $in->setSockOpt(
           ZMQ::SOCKOPT_SUBSCRIBE,
           rand(100000, 999999));
}
$in->connect("ipc:///tmp/events");
$i = 0;
while($i++ < 1000) {
  $who = $in->recv();
  $msg = $in->recv();
  printf("%s %s %s", $who, $msg, PHP_EOL);
}
                                cli ent.php
push   handler
  mongrel
                   pub

client client



mongrel 2
http://mongrel2.org/
$ctx = new ZMQContext();
$in = $ctx->getSocket(ZMQ::SOCKET_PULL);
$in->connect('tcp://localhost:9997');
$out = $ctx->getSocket(ZMQ::SOCKET_PUB);
$out->connect('tcp://localhost:9996');
$http = "HTTP/1.1 200 OKrnContent-Length:
%srnrn%s";

while(true) {
  $msg = $in->recv();
  list($uuid, $id, $path, $rest) =
                      explode(" ", $msg, 4);
  $res = $uuid." ".strlen($id).':'.$id.", ";
  $res .= sprintf($http, 6, "Hello!");
  $out->send($res);
}
                               handler.php
simple_handler = Handler(
  send_spec='tcp://*:9997',
  send_ident='ab206881-6f49-4276-9db1-1676bfae18b0',
  recv_spec='tcp://*:9996', recv_ident=''
)
main = Server(
  uuid="9e71cabf-6afb-4ee1-b550-7972245f7e0a",
  access_log="/logs/access.log",
  error_log="/logs/error.log",
  chroot="./",
  default_host="general.local",
  name="example",
  pid_file="/run/mongre2.pid",
  port=6767,
  hosts = [
    Host(name="general.local",
         routes={'/test':simple_handler})
  ]
)
settings = {"zeromq.threads": 1}
servers = [main]
namespace m2php;
$id ="82209006-86FF-4982-B5EA-D1E29E55D481";
$con = new m2phpConnection($id,
                    "tcp://127.0.0.1:9997",
                    "tcp://127.0.0.1:9996");
$ctx = new ZMQContext();
$in = $ctx->getSocket(ZMQ::SOCKET_SUB);
$in->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE,'');
$sub->connect('tcp://localhost:5566');
$poll = new ZMQPoll();
$poll->add($sub, ZMQ::POLL_IN);
$poll->add($con->reqs, ZMQ::POLL_IN);
$read = $write = $ids = array(); $snd = '';
$h = "HTTP/1.1 200 OKrnContent-Type: text/
htmlrnTransfer-Encoding: chunkedrnrn";

     https://github.com/winks/m2php
while (true) {
  $ev = $poll->poll($read, $write);
  foreach($read as $r) {
    if($r === $in) {
      $m = "<script type='text/javascript'>
       parent.updateChat('".$in->recv()."');
      </script>rn";
      $con->send($snd, implode(' ',$ids),
        sprintf("%xrn%s",strlen($m),$m));
    } else {
      $req = $con->recv();
      $snd = $req->sender;
      if($req->is_disconnect()) {
        unset($ids[$req->conn_id]);
      } else {
        $ids[$req->conn_id] = $req->conn_id;
        $con->send($snd, $req->conn_id,$h);
} } } }
Helpful Links
http://zero.mq
http://zguide.zero.mq
        Ian Barber nbarber/ZeroMQ-Talk
http://github.com/ia
        http://phpir.com
      ian.barber@gmail.com @ianbarber
http://joind.in/talk/view/2523



      thanks!

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction To RabbitMQ
Introduction To RabbitMQIntroduction To RabbitMQ
Introduction To RabbitMQKnoldus Inc.
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebBryan Helmig
 
Introduction to AMQP Messaging with RabbitMQ
Introduction to AMQP Messaging with RabbitMQIntroduction to AMQP Messaging with RabbitMQ
Introduction to AMQP Messaging with RabbitMQDmitriy Samovskiy
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Project Reactor Now and Tomorrow
Project Reactor Now and TomorrowProject Reactor Now and Tomorrow
Project Reactor Now and TomorrowVMware Tanzu
 
Document Management: Opendocman and LAMP installation on Cent OS
Document Management: Opendocman and LAMP installation on Cent OSDocument Management: Opendocman and LAMP installation on Cent OS
Document Management: Opendocman and LAMP installation on Cent OSSiddharth Ram Dinesh
 
Network-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQNetwork-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQICS
 
Introduction to Apache ActiveMQ Artemis
Introduction to Apache ActiveMQ ArtemisIntroduction to Apache ActiveMQ Artemis
Introduction to Apache ActiveMQ ArtemisYoshimasa Tanabe
 
Messaging Standards and Systems - AMQP & RabbitMQ
Messaging Standards and Systems - AMQP & RabbitMQMessaging Standards and Systems - AMQP & RabbitMQ
Messaging Standards and Systems - AMQP & RabbitMQAll Things Open
 
React Context API
React Context APIReact Context API
React Context APINodeXperts
 
Kinh nghiệm triển khai Microservices tại Sapo.vn
Kinh nghiệm triển khai Microservices tại Sapo.vnKinh nghiệm triển khai Microservices tại Sapo.vn
Kinh nghiệm triển khai Microservices tại Sapo.vnDotnet Open Group
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoringGrokking VN
 
History & Practices for UniRx(EN)
History & Practices for UniRx(EN)History & Practices for UniRx(EN)
History & Practices for UniRx(EN)Yoshifumi Kawai
 
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and FanoutOpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and FanoutSaju Madhavan
 
並行計算の実践と理論
並行計算の実践と理論並行計算の実践と理論
並行計算の実践と理論gotoloop
 

Was ist angesagt? (20)

Introduction To RabbitMQ
Introduction To RabbitMQIntroduction To RabbitMQ
Introduction To RabbitMQ
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
 
Introduction to AMQP Messaging with RabbitMQ
Introduction to AMQP Messaging with RabbitMQIntroduction to AMQP Messaging with RabbitMQ
Introduction to AMQP Messaging with RabbitMQ
 
RabbitMQ.ppt
RabbitMQ.pptRabbitMQ.ppt
RabbitMQ.ppt
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Project Reactor Now and Tomorrow
Project Reactor Now and TomorrowProject Reactor Now and Tomorrow
Project Reactor Now and Tomorrow
 
Document Management: Opendocman and LAMP installation on Cent OS
Document Management: Opendocman and LAMP installation on Cent OSDocument Management: Opendocman and LAMP installation on Cent OS
Document Management: Opendocman and LAMP installation on Cent OS
 
Network-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQNetwork-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQ
 
Introduction to Apache ActiveMQ Artemis
Introduction to Apache ActiveMQ ArtemisIntroduction to Apache ActiveMQ Artemis
Introduction to Apache ActiveMQ Artemis
 
Messaging Standards and Systems - AMQP & RabbitMQ
Messaging Standards and Systems - AMQP & RabbitMQMessaging Standards and Systems - AMQP & RabbitMQ
Messaging Standards and Systems - AMQP & RabbitMQ
 
React Context API
React Context APIReact Context API
React Context API
 
How MQTT work ?
How MQTT work ?How MQTT work ?
How MQTT work ?
 
Kinh nghiệm triển khai Microservices tại Sapo.vn
Kinh nghiệm triển khai Microservices tại Sapo.vnKinh nghiệm triển khai Microservices tại Sapo.vn
Kinh nghiệm triển khai Microservices tại Sapo.vn
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
Rabbitmq basics
Rabbitmq basicsRabbitmq basics
Rabbitmq basics
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoring
 
History & Practices for UniRx(EN)
History & Practices for UniRx(EN)History & Practices for UniRx(EN)
History & Practices for UniRx(EN)
 
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and FanoutOpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
 
Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
 
並行計算の実践と理論
並行計算の実践と理論並行計算の実践と理論
並行計算の実践と理論
 

Ähnlich wie ZeroMQ Is The Answer

ZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionIan Barber
 
ZeroMQ Is The Answer: PHP Tek 11 Version
ZeroMQ Is The Answer: PHP Tek 11 VersionZeroMQ Is The Answer: PHP Tek 11 Version
ZeroMQ Is The Answer: PHP Tek 11 VersionIan Barber
 
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoIntroduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoMasahiro Nagano
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challengervanphp
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleIan Barber
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationrjsmelo
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked aboutTatsuhiko Miyagawa
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Jakub Zalas
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges✅ William Pinaud
 
Micropage in microtime using microframework
Micropage in microtime using microframeworkMicropage in microtime using microframework
Micropage in microtime using microframeworkRadek Benkel
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Kacper Gunia
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUNCong Zhang
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowKacper Gunia
 
Javascript Continues Integration in Jenkins with AngularJS
Javascript Continues Integration in Jenkins with AngularJSJavascript Continues Integration in Jenkins with AngularJS
Javascript Continues Integration in Jenkins with AngularJSLadislav Prskavec
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Masahiro Nagano
 

Ähnlich wie ZeroMQ Is The Answer (20)

ZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 Version
 
ZeroMQ Is The Answer: PHP Tek 11 Version
ZeroMQ Is The Answer: PHP Tek 11 VersionZeroMQ Is The Answer: PHP Tek 11 Version
ZeroMQ Is The Answer: PHP Tek 11 Version
 
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoIntroduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challenger
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made Simple
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges
 
Micropage in microtime using microframework
Micropage in microtime using microframeworkMicropage in microtime using microframework
Micropage in microtime using microframework
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUN
 
Perl Web Client
Perl Web ClientPerl Web Client
Perl Web Client
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Javascript Continues Integration in Jenkins with AngularJS
Javascript Continues Integration in Jenkins with AngularJSJavascript Continues Integration in Jenkins with AngularJS
Javascript Continues Integration in Jenkins with AngularJS
 
ReactPHP
ReactPHPReactPHP
ReactPHP
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
 

Mehr von Ian Barber

How to stand on the shoulders of giants
How to stand on the shoulders of giantsHow to stand on the shoulders of giants
How to stand on the shoulders of giantsIan Barber
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersIan Barber
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionIan Barber
 
Deployment Tactics
Deployment TacticsDeployment Tactics
Deployment TacticsIan Barber
 
In Search Of: Integrating Site Search (PHP Barcelona)
In Search Of: Integrating Site Search (PHP Barcelona)In Search Of: Integrating Site Search (PHP Barcelona)
In Search Of: Integrating Site Search (PHP Barcelona)Ian Barber
 
Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & ToolsIan Barber
 
In Search Of... (Dutch PHP Conference 2010)
In Search Of... (Dutch PHP Conference 2010)In Search Of... (Dutch PHP Conference 2010)
In Search Of... (Dutch PHP Conference 2010)Ian Barber
 
In Search Of... integrating site search
In Search Of... integrating site search In Search Of... integrating site search
In Search Of... integrating site search Ian Barber
 
Document Classification In PHP - Slight Return
Document Classification In PHP - Slight ReturnDocument Classification In PHP - Slight Return
Document Classification In PHP - Slight ReturnIan Barber
 
Document Classification In PHP
Document Classification In PHPDocument Classification In PHP
Document Classification In PHPIan Barber
 

Mehr von Ian Barber (10)

How to stand on the shoulders of giants
How to stand on the shoulders of giantsHow to stand on the shoulders of giants
How to stand on the shoulders of giants
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Deployment Tactics
Deployment TacticsDeployment Tactics
Deployment Tactics
 
In Search Of: Integrating Site Search (PHP Barcelona)
In Search Of: Integrating Site Search (PHP Barcelona)In Search Of: Integrating Site Search (PHP Barcelona)
In Search Of: Integrating Site Search (PHP Barcelona)
 
Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & Tools
 
In Search Of... (Dutch PHP Conference 2010)
In Search Of... (Dutch PHP Conference 2010)In Search Of... (Dutch PHP Conference 2010)
In Search Of... (Dutch PHP Conference 2010)
 
In Search Of... integrating site search
In Search Of... integrating site search In Search Of... integrating site search
In Search Of... integrating site search
 
Document Classification In PHP - Slight Return
Document Classification In PHP - Slight ReturnDocument Classification In PHP - Slight Return
Document Classification In PHP - Slight Return
 
Document Classification In PHP
Document Classification In PHPDocument Classification In PHP
Document Classification In PHP
 

Kürzlich hochgeladen

Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

ZeroMQ Is The Answer

  • 1. e r 3 e r s w /2 2 5 arb a n i ew ian b h e al k /v @ t r n/ t e .i m il.c o m is rb nd .co a a oi ir m B /j p g n p:/ /ph er@ Ia tt :/ rb h ttp a h n.b ia
  • 2. “0MQ is unbelievably cool – if you haven’t got a project that needs it, make one up” jon gifford - loggly
  • 3.
  • 4.
  • 5.
  • 6. queue esb pipeline async pub/sub gateway
  • 7. request/response $ctx = new ZMQContext(); rep.php $server = new ZMQSocket($ctx, ZMQ::SOCKET_REP); $server->bind("tcp://*:5454"); while(true) { $message = $server->recv(); $server->send($message . " World"); }
  • 8. request/response $ctx = new ZMQContext(); req.php $req = new ZMQSocket($ctx, ZMQ::SOCKET_REQ); $req->connect("tcp://localhost:5454"); $req->send("Hello"); echo $req->recv();
  • 9.
  • 10. import zmq rep.py context = zmq.Context() server = context.socket(zmq.REP) server.connect("tcp://localhost:5455") while True: message = server.recv() print "Sending", message, "Worldn" server.send(message + " World")
  • 12. wget http://download.zeromq.org/ zeromq-2.1.1.tar.gz tar xvzf zeromq-2.1.1.tar.gz cd zeromq-2.1.1/ ./configure make sudo make install pear channel-discover pear.zero.mq pecl install zero.mq/zmq-beta echo "extension=zmq.so" > /etc/php.d/zmq.ini http://github.com/zeromq/zeromq2
  • 13. atomic string multipart messaging
  • 14. Post Office Image: http://www.flickr.com/photos/10804218@N00/4315282973 Post Box Image: http://www.flickr.com/photos/kenjonbro/3027166169
  • 15.
  • 16. queue
  • 17. queue $ctx = new ZMQContext(); $front = $ctx->getSocket(ZMQ::SOCKET_XREP); $back = $ctx->getSocket(ZMQ::SOCKET_XREQ); $front->bind('tcp://*:5454'); $back->bind ('tcp://*:5455'); $poll = new ZMQPoll(); $poll->add($front, ZMQ::POLL_IN); $poll->add($back, ZMQ::POLL_IN); $read = $write = array(); $snd = ZMQ::MODE_SNDMORE; $rcv = ZMQ::SOCKOPT_RCVMORE; queu e.php
  • 18. while(true) { $events = $poll->poll($read, $write); foreach($read as $socket) { if($socket === $front) { do { $msg = $front->recv(); $more = $front->getSockOpt($rcv); $back->send($msg, $more ? $snd:0); } while($more); } else if($socket === $back) { do { $msg = $back->recv(); $more = $back->getSockOpt($rcv); $front->send($msg, $more ? $snd:0); } while($more); }}}
  • 19. 0MQ1 0MQ2 Socket STDIN POLL events
  • 20. $ctx = new ZMQContext(); $sock = $ctx->getSocket(ZMQ::SOCKET_PULL); $sock->bind("tcp://*:5555"); $fh = fopen("php://stdin", 'r'); $poll = new ZMQPoll(); $poll->add($sock, ZMQ::POLL_IN); $poll->add($fh, ZMQ::POLL_IN); while(true) { $events = $poll->poll($read, $write); if($read[0] === $sock) { echo "ZMQ: ", $read[0]->recv(); } else { echo "STDIN: ", fgets($read[0]); }} poll.php
  • 21.
  • 22. stable / unstable Image: http://www.flickr.com/photos/pelican/235461339/
  • 24. pipeline define("NUM_WORKERS", 10); for($i = 0; $i < NUM_WORKERS; $i++) { if(pcntl_fork() == 0) { `php work.php`; exit; } } con troller.php $ctx = new ZMQContext(); $work = $ctx->getSocket(ZMQ::SOCKET_PUSH); $ctrl = $ctx->getSocket(ZMQ::SOCKET_PUSH); $work->setSockOpt(ZMQ::SOCKOPT_HWM, 10); $ctrl->setSockOpt(ZMQ::SOCKOPT_HWM, 1);
  • 25. $work->bind("ipc:///tmp/work"); $ctrl->bind("ipc:///tmp/control"); sleep(1); $fh = fopen('data.txt', 'r'); while($data = fgets($fh)) { $work->send($data); } for($i = 0; $i < NUM_WORKERS+1; $i++) { $ctrl->send("END"); }
  • 26. work.php $ctx = new ZMQContext(); $work = $ctx->getSocket(ZMQ::SOCKET_PULL); $work->setSockOpt(ZMQ::SOCKOPT_HWM, 1); $work->connect("ipc:///tmp/work"); $sink = $ctx->getSocket(ZMQ::SOCKET_PUSH); $sink->connect("ipc:///tmp/results"); $ctrl = $ctx->getSocket(ZMQ::SOCKET_PULL); $ctrl->setSockOpt(ZMQ::SOCKOPT_HWM, 1); $ctrl->connect("ipc:///tmp/control"); $poll = new ZMQPoll(); $poll->add($work, ZMQ::POLL_IN); $read = $write = array();
  • 27. while(true) { $ev = $poll->poll($read, $write, 5000); if($ev) { $message = $work->recv(); $sink->send(strlen($message)); } else { try { if($ctrl->recv(ZMQ::MODE_NOBLOCK)) { exit(); } } catch(ZMQException $e) { // noop } } }
  • 28. sink.php $ctx = new ZMQContext(); $res = $ctx->getSocket(ZMQ::SOCKET_PULL); $res->bind("ipc:///tmp/results"); $ctrl = $ctx->getSocket(ZMQ::SOCKET_PULL); $ctrl->setSockOpt(ZMQ::SOCKOPT_HWM, 1); $ctrl->connect("ipc:///tmp/control"); $poll = new ZMQPoll(); $poll->add($res, ZMQ::POLL_IN); $read = $write = array(); $total = 0;
  • 29. while(true) { $ev = $poll->poll($read, $write, 10000); if($ev) { $total += $res->recv(); } else { try { if($ctrl->recv(ZMQ::MODE_NOBLOCK)) { echo $total, PHP_EOL; exit(); } } catch (ZMQException $e) { //noop } } }
  • 30. $ php controller.php $ php sink.php Starting Worker 0 39694 Starting Worker 1 Starting Worker 2 Starting Worker 3 Starting Worker 4 Starting Worker 5 Starting Worker 6 Starting Worker 7 Starting Worker 8 Starting Worker 9
  • 32. im age up loaded for proc essing
  • 34. resizing and quan tizing
  • 37. pub/sub Image: http://www.flickr.com/photos/nikonvscanon/4519133003/
  • 39. pub send “h “hi” i” i” “h sub sub sub i” “h ted ann ned
  • 40. pub/sub $ctx = new ZMQContext(); $pub = $ctx->getSocket(ZMQ::SOCKET_PUB); $pub->bind('tcp://*:5566'); $pull = $ctx->getSocket(ZMQ::SOCKET_PULL); $pull->bind('tcp://*:5567'); while(true) { $message = $pull->recv(); $pub->send($message); } server.php
  • 41. $name = htmlspecialchars($_POST['name']); $msg =htmlspecialchars($_POST['message']); $ctx = new ZMQContext(); $send = $ctx->getSocket(ZMQ::SOCKET_PUSH); $send->connect('tcp://localhost:5567'); if($msg == 'm:joined') { $send->send( "<em>" . $name . " has joined</em>"); } else { $send->send($name . ': ' . $msg); } send.php
  • 42. $ctx = new ZMQContext(); $sub = $ctx->getSocket(ZMQ::SOCKET_SUB); $sub->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE,''); $sub->connect('tcp://localhost:5566'); $poll = new ZMQPoll(); $poll->add($sub, ZMQ::POLL_IN); $read = $wri = array(); while(true) { $ev = $poll->poll($read, $wri, 5000000); if($ev > 0) { echo "<script type='text/javascript'> parent.updateChat('"; echo $sub->recv() ."');</script>"; } ob_flush(); flush(); } ch at.php
  • 43.
  • 44. sub sub user data pub pub pub web web web
  • 45. $ctx = new ZMQContext(); $socket = $ctx->getSocket(ZMQ::SOCKET_PUB); $socket->connect("ipc:///tmp/usercache"); $socket->connect("ipc:///tmp/datacache"); $type = array('users', 'data'); while(true) { $socket->send($type[array_rand($type)], ZMQ::MODE_SNDMORE); $socket->send(rand(0, 12)); sleep(rand(0,3)); } cach e.php
  • 46. $ctx = new ZMQContext(); $socket = $ctx->getSocket(ZMQ::SOCKET_SUB); $socket->setSockOpt( ZMQ::SOCKOPT_SUBSCRIBE, "users"); $socket->bind("ipc:///tmp/usercache"); while(true) { $cache = $socket->recv(); $request = $socket->recv(); echo "Clearing $cache $requestn"; } userlistener.php
  • 47. types of transport inproc ipc tcp pgm
  • 48.
  • 49. distro sub web client sub web sub event sub sub web pub distro sub web client sub db
  • 50. $ctx = new ZMQContext(); $out = $ctx->getSocket(ZMQ::SOCKET_PUB); $out->setSockOpt(ZMQ::SOCKOPT_RATE, 10000); $out->connect("epgm://;239.192.0.1:7601"); $in = $ctx->getSocket(ZMQ::SOCKET_PULL); $in->bind("tcp://*:6767"); $device = new ZMQDevice( ZMQ::DEVICE_FORWARDER, $in, $out); eventhub.php
  • 51. $ctx = new ZMQContext(); $in = $ctx->getSocket(ZMQ::SOCKET_SUB); $in->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, ''); $in->setSockOpt(ZMQ::SOCKOPT_RATE, 10000); $in->connect("epgm://;239.192.0.1:7601"); $out = $ctx->getSocket(ZMQ::SOCKET_PUB); $out->bind("ipc:///tmp/events"); $device = new ZMQDevice( ZMQ::DEVICE_FORWARDER, $in, $out); distro.php
  • 52. $ctx = new ZMQContext(); $in = $ctx->getSocket(ZMQ::SOCKET_SUB); for($i = 0; $i<100; $i++) { $in->setSockOpt( ZMQ::SOCKOPT_SUBSCRIBE, rand(100000, 999999)); } $in->connect("ipc:///tmp/events"); $i = 0; while($i++ < 1000) { $who = $in->recv(); $msg = $in->recv(); printf("%s %s %s", $who, $msg, PHP_EOL); } cli ent.php
  • 53. push handler mongrel pub client client mongrel 2 http://mongrel2.org/
  • 54. $ctx = new ZMQContext(); $in = $ctx->getSocket(ZMQ::SOCKET_PULL); $in->connect('tcp://localhost:9997'); $out = $ctx->getSocket(ZMQ::SOCKET_PUB); $out->connect('tcp://localhost:9996'); $http = "HTTP/1.1 200 OKrnContent-Length: %srnrn%s"; while(true) { $msg = $in->recv(); list($uuid, $id, $path, $rest) = explode(" ", $msg, 4); $res = $uuid." ".strlen($id).':'.$id.", "; $res .= sprintf($http, 6, "Hello!"); $out->send($res); } handler.php
  • 55. simple_handler = Handler( send_spec='tcp://*:9997', send_ident='ab206881-6f49-4276-9db1-1676bfae18b0', recv_spec='tcp://*:9996', recv_ident='' ) main = Server( uuid="9e71cabf-6afb-4ee1-b550-7972245f7e0a", access_log="/logs/access.log", error_log="/logs/error.log", chroot="./", default_host="general.local", name="example", pid_file="/run/mongre2.pid", port=6767, hosts = [ Host(name="general.local", routes={'/test':simple_handler}) ] ) settings = {"zeromq.threads": 1} servers = [main]
  • 56. namespace m2php; $id ="82209006-86FF-4982-B5EA-D1E29E55D481"; $con = new m2phpConnection($id, "tcp://127.0.0.1:9997", "tcp://127.0.0.1:9996"); $ctx = new ZMQContext(); $in = $ctx->getSocket(ZMQ::SOCKET_SUB); $in->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE,''); $sub->connect('tcp://localhost:5566'); $poll = new ZMQPoll(); $poll->add($sub, ZMQ::POLL_IN); $poll->add($con->reqs, ZMQ::POLL_IN); $read = $write = $ids = array(); $snd = ''; $h = "HTTP/1.1 200 OKrnContent-Type: text/ htmlrnTransfer-Encoding: chunkedrnrn"; https://github.com/winks/m2php
  • 57. while (true) { $ev = $poll->poll($read, $write); foreach($read as $r) { if($r === $in) { $m = "<script type='text/javascript'> parent.updateChat('".$in->recv()."'); </script>rn"; $con->send($snd, implode(' ',$ids), sprintf("%xrn%s",strlen($m),$m)); } else { $req = $con->recv(); $snd = $req->sender; if($req->is_disconnect()) { unset($ids[$req->conn_id]); } else { $ids[$req->conn_id] = $req->conn_id; $con->send($snd, $req->conn_id,$h); } } } }
  • 58. Helpful Links http://zero.mq http://zguide.zero.mq Ian Barber nbarber/ZeroMQ-Talk http://github.com/ia http://phpir.com ian.barber@gmail.com @ianbarber http://joind.in/talk/view/2523 thanks!