@@ -36,7 +36,7 @@ class RdKafkaContext implements Context
36
36
private $ conf ;
37
37
38
38
/**
39
- * @var Producer
39
+ * @var RdKafkaProducer
40
40
*/
41
41
private $ producer ;
42
42
@@ -50,9 +50,6 @@ class RdKafkaContext implements Context
50
50
*/
51
51
private $ rdKafkaConsumers ;
52
52
53
- /**
54
- * @param array $config
55
- */
56
53
public function __construct (array $ config )
57
54
{
58
55
$ this ->config = $ config ;
@@ -96,7 +93,23 @@ public function createTemporaryQueue(): Queue
96
93
*/
97
94
public function createProducer (): Producer
98
95
{
99
- return new RdKafkaProducer ($ this ->getProducer (), $ this ->getSerializer ());
96
+ if (!isset ($ this ->producer )) {
97
+ $ producer = new VendorProducer ($ this ->getConf ());
98
+
99
+ if (isset ($ this ->config ['log_level ' ])) {
100
+ $ producer ->setLogLevel ($ this ->config ['log_level ' ]);
101
+ }
102
+
103
+ $ this ->producer = new RdKafkaProducer ($ producer , $ this ->getSerializer ());
104
+
105
+ // Once created RdKafkaProducer can store messages internally that need to be delivered before PHP shuts
106
+ // down. Otherwise, we are bound to lose messages in transit.
107
+ // Note that it is generally preferable to call "close" method explicitly before shutdown starts, since
108
+ // otherwise we might not have access to some objects, like database connections.
109
+ register_shutdown_function ([$ this ->producer , 'flush ' ], $ this ->config ['shutdown_timeout ' ] ?? -1 );
110
+ }
111
+
112
+ return $ this ->producer ;
100
113
}
101
114
102
115
/**
@@ -139,6 +152,11 @@ public function close(): void
139
152
foreach ($ kafkaConsumers as $ kafkaConsumer ) {
140
153
$ kafkaConsumer ->unsubscribe ();
141
154
}
155
+
156
+ // Compatibility with phprdkafka 4.0.
157
+ if (isset ($ this ->producer )) {
158
+ $ this ->producer ->flush ($ this ->config ['shutdown_timeout ' ] ?? -1 );
159
+ }
142
160
}
143
161
144
162
public function createSubscriptionConsumer (): SubscriptionConsumer
@@ -163,19 +181,6 @@ public static function getLibrdKafkaVersion(): string
163
181
return "$ major. $ minor. $ patch " ;
164
182
}
165
183
166
- private function getProducer (): VendorProducer
167
- {
168
- if (null === $ this ->producer ) {
169
- $ this ->producer = new VendorProducer ($ this ->getConf ());
170
-
171
- if (isset ($ this ->config ['log_level ' ])) {
172
- $ this ->producer ->setLogLevel ($ this ->config ['log_level ' ]);
173
- }
174
- }
175
-
176
- return $ this ->producer ;
177
- }
178
-
179
184
private function getConf (): Conf
180
185
{
181
186
if (null === $ this ->conf ) {
0 commit comments