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?

EBPF and Linux Networking
EBPF and Linux NetworkingEBPF and Linux Networking
EBPF and Linux NetworkingPLUMgrid
 
Understanding Open vSwitch
Understanding Open vSwitch Understanding Open vSwitch
Understanding Open vSwitch YongKi Kim
 
TRex Realistic Traffic Generator - Stateless support
TRex  Realistic Traffic Generator  - Stateless support TRex  Realistic Traffic Generator  - Stateless support
TRex Realistic Traffic Generator - Stateless support Hanoch Haim
 
Linux network stack
Linux network stackLinux network stack
Linux network stackTakuya ASADA
 
Introduction To RabbitMQ
Introduction To RabbitMQIntroduction To RabbitMQ
Introduction To RabbitMQKnoldus Inc.
 
DockerCon 2017 - Cilium - Network and Application Security with BPF and XDP
DockerCon 2017 - Cilium - Network and Application Security with BPF and XDPDockerCon 2017 - Cilium - Network and Application Security with BPF and XDP
DockerCon 2017 - Cilium - Network and Application Security with BPF and XDPThomas Graf
 
Mqtt overview (iot)
Mqtt overview (iot)Mqtt overview (iot)
Mqtt overview (iot)David Fowler
 
Monitoring and problem determination of your mq distributed systems
Monitoring and problem determination of your mq distributed systemsMonitoring and problem determination of your mq distributed systems
Monitoring and problem determination of your mq distributed systemsmatthew1001
 
Introduction to eBPF and XDP
Introduction to eBPF and XDPIntroduction to eBPF and XDP
Introduction to eBPF and XDPlcplcp1
 
FD.IO Vector Packet Processing
FD.IO Vector Packet ProcessingFD.IO Vector Packet Processing
FD.IO Vector Packet ProcessingKernel TLV
 
A Kernel of Truth: Intrusion Detection and Attestation with eBPF
A Kernel of Truth: Intrusion Detection and Attestation with eBPFA Kernel of Truth: Intrusion Detection and Attestation with eBPF
A Kernel of Truth: Intrusion Detection and Attestation with eBPFoholiab
 
MQTT - A practical protocol for the Internet of Things
MQTT - A practical protocol for the Internet of ThingsMQTT - A practical protocol for the Internet of Things
MQTT - A practical protocol for the Internet of ThingsBryan Boyd
 
Scapyで作る・解析するパケット
Scapyで作る・解析するパケットScapyで作る・解析するパケット
Scapyで作る・解析するパケットTakaaki Hoyo
 

Was ist angesagt? (20)

EBPF and Linux Networking
EBPF and Linux NetworkingEBPF and Linux Networking
EBPF and Linux Networking
 
Understanding Open vSwitch
Understanding Open vSwitch Understanding Open vSwitch
Understanding Open vSwitch
 
TRex Realistic Traffic Generator - Stateless support
TRex  Realistic Traffic Generator  - Stateless support TRex  Realistic Traffic Generator  - Stateless support
TRex Realistic Traffic Generator - Stateless support
 
RabbitMQ.ppt
RabbitMQ.pptRabbitMQ.ppt
RabbitMQ.ppt
 
gRPC Overview
gRPC OverviewgRPC Overview
gRPC Overview
 
Linux network stack
Linux network stackLinux network stack
Linux network stack
 
RabbitMQ
RabbitMQRabbitMQ
RabbitMQ
 
Introduction To RabbitMQ
Introduction To RabbitMQIntroduction To RabbitMQ
Introduction To RabbitMQ
 
DockerCon 2017 - Cilium - Network and Application Security with BPF and XDP
DockerCon 2017 - Cilium - Network and Application Security with BPF and XDPDockerCon 2017 - Cilium - Network and Application Security with BPF and XDP
DockerCon 2017 - Cilium - Network and Application Security with BPF and XDP
 
Mqtt overview (iot)
Mqtt overview (iot)Mqtt overview (iot)
Mqtt overview (iot)
 
Monitoring and problem determination of your mq distributed systems
Monitoring and problem determination of your mq distributed systemsMonitoring and problem determination of your mq distributed systems
Monitoring and problem determination of your mq distributed systems
 
RabbitMQ
RabbitMQ RabbitMQ
RabbitMQ
 
Introduction to eBPF and XDP
Introduction to eBPF and XDPIntroduction to eBPF and XDP
Introduction to eBPF and XDP
 
mTCP使ってみた
mTCP使ってみたmTCP使ってみた
mTCP使ってみた
 
FD.IO Vector Packet Processing
FD.IO Vector Packet ProcessingFD.IO Vector Packet Processing
FD.IO Vector Packet Processing
 
A Kernel of Truth: Intrusion Detection and Attestation with eBPF
A Kernel of Truth: Intrusion Detection and Attestation with eBPFA Kernel of Truth: Intrusion Detection and Attestation with eBPF
A Kernel of Truth: Intrusion Detection and Attestation with eBPF
 
美团技术团队 - KVM性能优化
美团技术团队 - KVM性能优化美团技术团队 - KVM性能优化
美团技术团队 - KVM性能优化
 
Message Broker System and RabbitMQ
Message Broker System and RabbitMQMessage Broker System and RabbitMQ
Message Broker System and RabbitMQ
 
MQTT - A practical protocol for the Internet of Things
MQTT - A practical protocol for the Internet of ThingsMQTT - A practical protocol for the Internet of Things
MQTT - A practical protocol for the Internet of Things
 
Scapyで作る・解析するパケット
Scapyで作る・解析するパケットScapyで作る・解析するパケット
Scapyで作る・解析するパケット
 

Ä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

Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sectoritnewsafrica
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 

Kürzlich hochgeladen (20)

Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 

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!