优化一下代码: private void initDelayThread() { for (;;){ AsyncTaskLog first; try { first = delayQueue.take(); KakfaProductBaseProperties kafkaProperties = kafkaProduct.getKafkaProperties(first.getSystemName(), first.getTopicName()); log.info("----------------RetryAspect 消息发送:{}", JSON.toJSONString(first)); if(Objects.nonNull(kafkaProperties)) { kafkaProduct.sendSingleString(kafkaProperties, JSON.toJSONString(first)); }else { continue; } } catch (InterruptedException e) { log.error("init application error:{}", e ); return; } } }
时间: 2024-02-14 09:26:26 浏览: 23
你的代码中,主要是一个无限循环,从 `delayQueue` 中取出任务并发送给 Kafka。在优化代码时,可以考虑以下几点:
1. 为了避免代码的可读性下降,可以使用 `while (true)` 替代 `for (;;)`,使代码更易于理解。
2. 你可以将获取 `kafkaProperties` 和发送消息的逻辑提取为一个独立的方法,以提高代码的可读性和可维护性。
3. 在捕获 `InterruptedException` 时,可以使用日志记录错误信息,并考虑是否需要做其他处理。
根据以上建议,优化后的代码如下所示:
```java
private void initDelayThread() {
while (true) {
AsyncTaskLog first;
try {
first = delayQueue.take();
sendToKafka(first);
} catch (InterruptedException e) {
log.error("init application error: {}", e);
return;
}
}
}
private void sendToKafka(AsyncTaskLog taskLog) {
KakfaProductBaseProperties kafkaProperties = kafkaProduct.getKafkaProperties(taskLog.getSystemName(), taskLog.getTopicName());
log.info("----------------RetryAspect 消息发送: {}", JSON.toJSONString(taskLog));
if (Objects.nonNull(kafkaProperties)) {
kafkaProduct.sendSingleString(kafkaProperties, JSON.toJSONString(taskLog));
}
}
```
通过将发送消息的逻辑提取为一个独立的方法,使代码更加清晰和易于阅读。同时,通过使用 `while (true)` 替代 `for (;;)`,增加了代码的可读性和可维护性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)