1+ <?php
2+
3+ use Pulsar \Compression \Compression ;
4+ use Pulsar \Exception \IOException ;
5+ use Pulsar \Exception \OptionsException ;
6+ use Pulsar \Producer ;
7+ use Pulsar \ProducerOptions ;
8+ use Swoole \Http \Response ;
9+ use Swoole \Http \Server ;
10+
11+ require_once __DIR__ . '/../vendor/autoload.php ' ;
12+
13+
14+
15+ /**
16+ * Class ProducerStore
17+ */
18+ class ProducerStore
19+ {
20+
21+ /**
22+ * @var array<string,Producer>
23+ */
24+ protected static $ inner = [];
25+
26+
27+ /**
28+ * @param string $topic
29+ * @return Producer
30+ * @throws IOException
31+ * @throws OptionsException
32+ * @throws \Pulsar\Exception\RuntimeException
33+ */
34+ public static function get (string $ topic ): Producer
35+ {
36+ if (!isset (self ::$ inner [ $ topic ])) {
37+ self ::create ($ topic );
38+ }
39+
40+ return self ::$ inner [ $ topic ];
41+ }
42+
43+
44+ /**
45+ * @param string $topic
46+ * @return void
47+ * @throws IOException
48+ * @throws OptionsException
49+ * @throws \Pulsar\Exception\RuntimeException
50+ */
51+ private static function create (string $ topic )
52+ {
53+ $ options = new ProducerOptions ();
54+
55+ // If permission authentication is available
56+ // Only JWT authentication is currently supported
57+ // $options->setAuthentication(new Jwt('token'));
58+
59+ $ options ->setConnectTimeout (3 );
60+ $ options ->setTopic ($ topic );
61+ $ options ->setCompression (Compression::ZLIB );
62+ $ options ->setKeepalive (true );
63+ $ producer = new Producer ('pulsar://localhost:6650 ' , $ options );
64+ $ producer ->connect ();
65+
66+ self ::$ inner [ $ topic ] = $ producer ;
67+ }
68+ }
69+
70+
71+ $ server = new Server ('0.0.0.0 ' , 1234 );
72+ $ server ->set ([
73+ 'enable_coroutine ' => true ,
74+ 'hook_flags ' => SWOOLE_HOOK_ALL ,
75+ ]);
76+
77+ $ server ->on ('request ' , function ($ req , Response $ resp ) {
78+
79+ // Should be taken from here to keep this connection from being closed
80+ $ producer = ProducerStore::get ('persistent://public/default/demo ' );
81+
82+ $ id = $ producer ->send ('hello ' );
83+ $ resp ->end (json_encode (['id ' => $ id ]));
84+ });
85+
86+ $ server ->start ();
0 commit comments