浙江省网站建设_网站建设公司_前端开发_seo优化
2025/12/30 19:44:12 网站建设 项目流程

不会“自动”把 **消息过大** 的报错打出来,
**除非你主动去拿发送结果**,否则 `template.send(...)` 只是 **异步把消息放进客户端缓冲区**,
当消息 **> max.request.size / message.max.bytes** 时,生产者会收到 `RecordTooLargeException`,
但这段代码 **没有任何回调或 `.get()`**,异常就 **安静地躺在客户端内部** 不会被打印,
于是看起来就像“消息丢了”。

---

### 1. 当前代码的隐患
```java
template.send(userTopic, model.getPlstx(), msg); // 异步发
log.info("sync user:{}", msg); // 立即打印
return true; // 永远返回 true
```
- 发送失败(太大、网络抖动、队列满)→ **回调没人管**,异常没人看。
- 日志里只能看到 **“sync user:……”**,看不到任何错误,**运维会以为“已发出”**。

---

### 2. 如何立刻把“过大”错误暴露出来

#### ① 最简单:同步等结果(阻塞 5 秒)
```java
try {
SendResult<String, String> result = template
.send(userTopic, model.getPlstx(), msg)
.get(5, TimeUnit.SECONDS); // 立即把异步变同步
log.info("sync user ok, offset={}", result.getRecordMetadata().offset());
return true;
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("sync user failed, msg size={}", msg.getBytes(StandardCharsets.UTF_8).length, e);
return false;
}
```
- 消息 **> 1 MB** 时会直接抛 `ExecutionException: RecordTooLargeException`,日志就能看见。
- 不影响主流程,只是多等 5 秒;重试策略仍由 Kafka 客户端自己完成。

#### ② 非阻塞回调(不卡点)
```java
template.send(userTopic, model.getPlstx(), msg)
.addCallback(
r -> log.info("sync user ok, offset={}", r.getRecordMetadata().offset()),
e -> log.error("sync user failed, msg size={}",
msg.getBytes(StandardCharsets.UTF_8).length, e)
);
return true; // 先返回,错误在回调里打
```
> 既不会阻塞业务线程,也能把 **RecordTooLargeException** 打出来。

---

### 3. 一键验证
1. 把 `msg` 手动拼到 **1.5 MB**(复制几万字符即可)。
2. 用 **① 同步** 方式调用,日志立即出现:
```
sync user failed, msg size=1572864
org.apache.kafka.common.errors.RecordTooLargeException: The message is 1572864 bytes when serialized which is larger than the maximum request size you have configured with the max.request.size configuration.
```
3. 调大生产者配置后重试即可成功:
```yaml
spring:
kafka:
producer:
max-request-size: 10485760 # 10 MB
compression-type: snappy
```

---

### 4. 结论
> **当前代码不会主动把“消息过大”报错打出来,因为没调用 `.get()` 也没加回调;**
> **加上 `.get(5, TimeUnit.SECONDS)` 或 `addCallback` 后,一旦超过 `max.request.size` 就会立即在日志里看到 `RecordTooLargeException`,从而真正发现“为什么消息没到”。**

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询