基于 Claude Code 重构 Jakarta EE 消息队列 Java 生产者代码
本文记录了使用 Claude Code 智能助手对 Jakarta EE 消息队列 Java 生产者代码进行优化的过程。原代码同时支持 Queue 和 Topic,但在客户实际环境中通常仅使用 Queue。目标是将代码简化为仅处理 Queue,提高可读性。
任务背景
此前曾在网页端测试过类似指令,但本次在本地终端环境中执行。由于环境限制未包含完整的测试步骤,主要关注代码逻辑的修正。
交互过程
1. 启动与项目分析
[root@rocky9 my-mq-app]# claude
模型识别出这是一个 Jakarta JMS 生产者示例,功能包括向队列或主题发送文本消息及控制消息。
2. 修改指令
指令: 将代码改为只处理 Queue,移除 Topic 相关逻辑,提高代码可读性。
AI 执行结果摘要:
- 移除了
Topic类型的导入与资源注入。 - 简化了命令行参数解析,不再需要指定
queue或topic类型。 - 更新了类名注释及主方法逻辑。
3. 关键变更 Diff
移除 Topic 依赖
-import jakarta.jms.Topic;
-@Resource(lookup = "jms/MyTopic")
-private static Topic topic;
简化参数校验
- if ((args.length < 1) || (args.length > 2)) {
- String destType = args[0];
- // ... 检查 queue/topic 类型
- }
+ if (args.length > 1) {
+ System.err.println("Program takes at most one argument: [<number-of-messages>]");
+ System.exit(1);
+ }
更新类名与注释
-public class Producer {
+public class QueueProducer {
4. 最终代码验证
修改完成后,通过 cat 命令查看最终文件内容:
/*
* Copyright (c), Eclipse Foundation, Inc. and its licensors.
*
* All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v1.0, which is available at
* https://www.eclipse.org/org/documents/edl-v10.php
*
* SPDX-License-Identifier: BSD-3-Clause
*/
jakarta.tutorial.producer;
jakarta.annotation.Resource;
jakarta.jms.ConnectionFactory;
jakarta.jms.Destination;
jakarta.jms.JMSContext;
jakarta.jms.JMSRuntimeException;
jakarta.jms.Queue;
{
ConnectionFactory connectionFactory;
Queue queue;
{
(args.length > ) {
System.err.println(
);
System.exit();
}
;
(args.length == ) {
{
numMsgs = Integer.parseInt(args[]);
(numMsgs <= ) {
System.err.println( + numMsgs);
System.exit();
}
} (NumberFormatException e) {
System.err.println( + args[]);
System.exit();
}
}
numMsgs;
queue;
( connectionFactory.createContext();) {
;
( ; i < NUM_MSGS; i++) {
+ (i + )
+ ;
System.out.println( + message);
context.createProducer().send(dest, message);
count += ;
}
System.out.println( + count);
context.createProducer().send(dest, context.createMessage());
} (JMSRuntimeException e) {
System.err.println( + e.toString());
System.exit();
}
System.exit();
}
}

