forked from rabbitmq/rabbitmq-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_server.php
84 lines (65 loc) · 1.68 KB
/
rpc_server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
function fib($n) {
if($n == 0)
return 0;
if($n == 1)
return 1;
return fib($n - 1) + fib($n - 2);
}
function fast_fib($n) {
if ($n < 0)
throw new Exception('Negative number not implemented');
else
return fast_fib_calc($n)[0];
}
function fast_fib_calc($n) {
if ($n == 0)
return array(0, 1);
else {
list($a,$b) = fast_fib_calc(floor($n/2));
$c = $a * ($b * 2 - $a);
$d = $a * $a + $b * $b;
if (($n % 2) == 0)
return array($c, $d);
else
return array($d, $c + $d);
}
}
//Establish connection to AMQP
$connection = new AMQPConnection();
$connection->setHost('127.0.0.1');
$connection->setLogin('guest');
$connection->setPassword('guest');
$connection->connect();
//Declare Channel
$channel = new AMQPChannel($connection);
$channel->setPrefetchCount(1);
$exchange = new AMQPExchange($channel);
$queueName = 'rpc_queue';
$queue = new AMQPQueue($channel);
$queue->setName($queueName);
$queue->declareQueue();
echo " [x] Awaiting RPC requests", PHP_EOL;
$callback_func = function(AMQPEnvelope $message, AMQPQueue $q) use (&$exchange) {
$n = intval($message->getBody());
echo " [.] fib({$n})", PHP_EOL;
$attributes = array(
'correlation_id' => $message->getCorrelationId()
);
echo sprintf(" QueueName: %s", $q->getName()), PHP_EOL;
echo sprintf(" ReplyTo: %s", $message->getReplyTo()), PHP_EOL;
echo sprintf(" CorrelationID: %s", $message->getCorrelationId()), PHP_EOL;
$exchange->publish( (string)fast_fib($n),
$message->getReplyTo(),
AMQP_NOPARAM,
$attributes
);
$q->nack($message->getDeliveryTag());
};
try {
$queue->consume($callback_func);
} catch(AMQPQueueException $ex) {
print_r($ex);
} catch(Exception $ex) {
print_r($ex);
}