-
Notifications
You must be signed in to change notification settings - Fork 10
/
producer-keepalive.php
86 lines (66 loc) · 1.95 KB
/
producer-keepalive.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
<?php
use Pulsar\Compression\Compression;
use Pulsar\Exception\IOException;
use Pulsar\Exception\OptionsException;
use Pulsar\Producer;
use Pulsar\ProducerOptions;
use Swoole\Http\Response;
use Swoole\Http\Server;
require_once __DIR__ . '/../vendor/autoload.php';
/**
* Class ProducerStore
*/
class ProducerStore
{
/**
* @var array<string,Producer>
*/
protected static $inner = [];
/**
* @param string $topic
* @return Producer
* @throws IOException
* @throws OptionsException
* @throws \Pulsar\Exception\RuntimeException
*/
public static function get(string $topic): Producer
{
if (!isset(self::$inner[ $topic ])) {
self::create($topic);
}
return self::$inner[ $topic ];
}
/**
* @param string $topic
* @return void
* @throws IOException
* @throws OptionsException
* @throws \Pulsar\Exception\RuntimeException
*/
private static function create(string $topic)
{
$options = new ProducerOptions();
// If permission authentication is available
// Only JWT authentication is currently supported
// $options->setAuthentication(new Jwt('token'));
$options->setConnectTimeout(3);
$options->setTopic($topic);
$options->setCompression(Compression::ZLIB);
$options->setKeepalive(true);
$producer = new Producer('pulsar://localhost:6650', $options);
$producer->connect();
self::$inner[ $topic ] = $producer;
}
}
$server = new Server('0.0.0.0', 1234);
$server->set([
'enable_coroutine' => true,
'hook_flags' => SWOOLE_HOOK_ALL,
]);
$server->on('request', function ($req, Response $resp) {
// Should be taken from here to keep this connection from being closed
$producer = ProducerStore::get('persistent://public/default/demo');
$id = $producer->send('hello');
$resp->end(json_encode(['id' => $id]));
});
$server->start();