Skip to content

Commit 3e0a4b9

Browse files
committed
fix: 解决 producer send 的潜在内存泄露问题
1 parent 3e3faef commit 3e0a4b9

3 files changed

Lines changed: 10 additions & 3 deletions

File tree

lib/producer.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -533,11 +533,14 @@ Napi::Value RocketMQProducer::Send(const Napi::CallbackInfo& info) {
533533
std::unique_ptr<ProducerSendCallback> send_callback(
534534
new ProducerSendCallback(env, Napi::Persistent(Value()), info[3].As<Napi::Function>()));
535535

536+
// 先获取原始指针,但保持智能指针的所有权
537+
auto* raw_callback = send_callback.get();
536538
try {
537-
// 转移所有权给 RocketMQ,成功后智能指针释放所有权
538-
producer_.send(message, send_callback.release());
539+
producer_.send(message, raw_callback);
540+
// 只有在 send() 成功后才释放所有权
541+
send_callback.release();
539542
} catch (const std::exception& e) {
540-
// 如果发送失败,智能指针会自动清理回调对象
543+
// 失败时智能指针自动清理,无内存泄漏
541544
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
542545
return env.Undefined();
543546
}

lib/producer.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ class RocketMQProducer : public Napi::ObjectWrap<RocketMQProducer> {
5555
std::atomic<bool> is_started_{false};
5656
std::atomic<bool> is_shutting_down_{false};
5757
std::atomic<bool> is_destroyed_{false};
58+
// state_mutex_ 用于保护状态转换的原子性
59+
// 注意:start()/shutdown() 期间会持有锁,调用方应避免在回调中访问状态
5860
mutable std::mutex state_mutex_;
5961
};
6062

lib/push_consumer.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ class RocketMQPushConsumer : public Napi::ObjectWrap<RocketMQPushConsumer> {
6060
std::atomic<bool> is_started_{false};
6161
std::atomic<bool> is_shutting_down_{false};
6262
std::atomic<bool> is_destroyed_{false};
63+
// state_mutex_ 用于保护状态转换的原子性
64+
// 注意:start()/shutdown() 期间会持有锁,调用方应避免在回调中访问状态
6365
mutable std::mutex state_mutex_;
6466
};
6567

0 commit comments

Comments
 (0)