-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathsample.php
96 lines (72 loc) · 2.76 KB
/
sample.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
85
86
87
88
89
90
91
92
93
94
95
<?php
require "vendor/autoload.php";
use MQ\Model\TopicMessage;
use MQ\MQClient;
function getMillisecond() {
list($t1, $t2) = explode(' ', microtime());
return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
}
class Sample
{
private $client;
public function __construct($accessId, $accessKey, $endPoint)
{
$this->client = new MQClient($endPoint, $accessId, $accessKey);
}
public function run()
{
// get message producer
// 使用实例则带上实例ID,否则为:NULL,注意:默认实例不需要实例ID
$producer = $this->client->getProducer(NULL,"abc");
// get message consumer
$consumer = $this->client->getConsumer(NULL,"abc", "GID-abc");
while (True) {
// publish one message to topic abc
$topicMessage = $producer->publishMessage(
new TopicMessage("xxxxxxxx")
);
print "\npublish finish -> " . $topicMessage->getMessageId() . " " . $topicMessage->getMessageBodyMD5() . "\n";
try {
$messages = $consumer->consumeMessage(4, 3);
} catch (\Exception $e) {
if ($e instanceof MQ\Exception\MessageNotExistException) {
// no new message;
// long polling again.
print "no new message\n";
continue;
}
print_r($e->getMessage() . "\n");
sleep(3);
continue;
}
print "consume finish, messages:\n";
$receiptHandles = array();
foreach ($messages as $message) {
$receiptHandles[] = $message->getReceiptHandle();
$latency = getMillisecond() - $message->getPublishTime();
printf("ID:%s LAT:%d TAG:%s BODY:%s \nPublishTime:%d, FirstConsumeTime:%d, \nConsumedTimes:%d, NextConsumeTime:%d\n",
$message->getMessageId(), $latency, $message->getMessageTag(), $message->getMessageBody(),
$message->getPublishTime(), $message->getFirstConsumeTime(), $message->getConsumedTimes(), $message->getNextConsumeTime());
}
print_r($receiptHandles);
print_r($consumer->ackMessage($receiptHandles));
print "ack finish\n";
sleep(3);
print ".....................->>>>";
}
}
}
// Your Aliyun Access ID
$accessId = "";
// Your Aliyun Access Secret Key
$accessKey = "";
// Your Aliyun MQ Http Endpoint
$endPoint = "";
if (empty($accessId) || empty($accessKey) || empty($endPoint))
{
echo "Must Provide AccessId/AccessKey/EndPoint to Run the Example. \n";
return;
}
$instance = new Sample($accessId, $accessKey, $endPoint);
$instance->run();
?>