建生產(chǎn)級(jí)AI Agent)
1. 這不是“轉(zhuǎn)行”是Java工程師的自然進(jìn)化路徑最近三個(gè)月我陸續(xù)幫6位在銀行、電商、SaaS公司做后端開(kāi)發(fā)的Java老同事做了技術(shù)路徑梳理。他們共同的問(wèn)題不是“要不要學(xué)AI Agent”而是“怎么把十年積累的Spring Boot、MyBatis、分布式事務(wù)經(jīng)驗(yàn)不浪費(fèi)地用在AI智能體開(kāi)發(fā)上”。這恰恰是標(biāo)題里“Java工程師轉(zhuǎn)型AI Agent”最常被誤解的一點(diǎn)——它根本不是從零開(kāi)始學(xué)Python、重裝大腦而是一次精準(zhǔn)的能力遷移把你在高并發(fā)訂單系統(tǒng)里設(shè)計(jì)狀態(tài)機(jī)的經(jīng)驗(yàn)遷移到Agent的Thought-Action-Observation循環(huán)把你在支付網(wǎng)關(guān)里做的熔斷降級(jí)策略復(fù)用到LLM調(diào)用失敗時(shí)的Fallback機(jī)制甚至你寫(xiě)過(guò)的JUnit單元測(cè)試用例稍加改造就能變成Agent行為驗(yàn)證的黃金標(biāo)準(zhǔn)。核心關(guān)鍵詞其實(shí)就三個(gè)LangChain4j、Spring AI、ReAct。但它們不是孤立工具而是三層能力接口LangChain4j是Java生態(tài)的“膠水層”解決Java對(duì)象如何與LLM輸入輸出對(duì)齊Spring AI是企業(yè)級(jí)工程化封裝讓你能把Agent像Service一樣注入、配置、監(jiān)控ReAct則是底層決策范式它決定了你的Agent是機(jī)械地填槽位還是真能像人一樣“先思考再行動(dòng)”。比如我們團(tuán)隊(duì)上周上線的客服工單自動(dòng)歸因Agent核心邏輯就是ReAct看到用戶報(bào)錯(cuò)“訂單支付超時(shí)”它不會(huì)直接查數(shù)據(jù)庫(kù)而是先思考“超時(shí)可能由支付網(wǎng)關(guān)響應(yīng)慢、庫(kù)存鎖失敗、還是風(fēng)控?cái)r截導(dǎo)致”再針對(duì)性調(diào)用對(duì)應(yīng)API觀察結(jié)果最后生成歸因結(jié)論——這個(gè)過(guò)程和Java程序員寫(xiě)if-else鏈的本質(zhì)完全一致只是判斷條件從硬編碼變成了LLM推理。適合誰(shuí)讀如果你能熟練寫(xiě)出帶事務(wù)傳播的Service方法能看懂Spring AOP代理原理知道MyBatis一級(jí)二級(jí)緩存區(qū)別那這篇就是為你寫(xiě)的。不需要你背誦Transformer公式但得理解“token是什么意思”——它不是抽象概念而是你每天打交道的String長(zhǎng)度限制Qwen3.7模型單次請(qǐng)求最大8192 token相當(dāng)于你一個(gè)Transactional方法里最多處理8192個(gè)字符的業(yè)務(wù)描述超了就得切分或流式處理。后面所有實(shí)操細(xì)節(jié)都會(huì)錨定在Java工程師的真實(shí)工作場(chǎng)景里怎么用Value注入LLM配置、怎么給Agent加Dubbo泛化調(diào)用、怎么用SkyWalking追蹤一次ReAct循環(huán)耗時(shí)。這不是教你怎么當(dāng)AI研究員而是教你用Java的思維造出真正能進(jìn)生產(chǎn)環(huán)境的AI智能體。2. 為什么放棄Python生態(tài)Java系A(chǔ)gent框架的不可替代性2.1 企業(yè)級(jí)系統(tǒng)里的“隱形成本”才是關(guān)鍵戰(zhàn)場(chǎng)很多Java工程師第一次接觸LangChain時(shí)本能反應(yīng)是“Python版更成熟”。確實(shí)LangChain Py有更豐富的Tool生態(tài)但當(dāng)你真要把Agent嵌入一個(gè)日均千萬(wàn)訂單的交易系統(tǒng)時(shí)就會(huì)發(fā)現(xiàn)Python帶來(lái)的隱性成本遠(yuǎn)超想象。去年我們給某保險(xiǎn)核心系統(tǒng)做保單智能核保Agent初期用Python Flask封裝結(jié)果在壓測(cè)階段暴露三個(gè)致命問(wèn)題第一JVM進(jìn)程里混跑Python解釋器GC停頓時(shí)間從200ms飆升到1.2s觸發(fā)下游風(fēng)控服務(wù)熔斷第二Python依賴包版本沖突——TensorFlow 2.15和LangChain 0.1.0要求的Pydantic版本打架導(dǎo)致線上熱更新失敗第三也是最痛的Java團(tuán)隊(duì)要為Python服務(wù)單獨(dú)建一套Prometheus監(jiān)控告警而原有ELK日志體系完全無(wú)法解析Python堆棧。最終我們砍掉Python層用LangChain4j重寫(xiě)整個(gè)Agent模塊直接作為Spring Boot Starter引入GC停頓回歸正常監(jiān)控指標(biāo)自動(dòng)接入現(xiàn)有Dashboard運(yùn)維成本下降70%。LangChain4j的價(jià)值本質(zhì)是把LLM交互“Java化”它的ChatModel接口繼承自Spring的SmartInitializingSingleton意味著你可以像配置DataSource一樣配置LLM客戶端它的Message類繼承自Serializable天然支持Redis緩存序列化它的Tool抽象強(qiáng)制要求實(shí)現(xiàn)apply()方法并返回Result這和Java里定義Service接口的契約精神完全一致。舉個(gè)具體例子你要對(duì)接阿里云百煉Qwen3.7Python版需要pip install dashscope然后寫(xiě)一堆requests.post代碼而LangChain4j只需在application.yml里配spring: ai: alibaba: dashscope: api-key: ${DASHSCOPE_API_KEY} model: qwen-max base-url: https://dashscope.aliyuncs.com/api/v1然后Autowired注入ChatClient一行代碼調(diào)用ChatResponse response chatClient.call(new ChatRequest(分析這份保單風(fēng)險(xiǎn)等級(jí)));背后自動(dòng)完成HTTP Client初始化、Token自動(dòng)續(xù)期、響應(yīng)體反序列化——這些正是Java工程師最熟悉的Spring Boot自動(dòng)裝配魔法。2.2 Spring AI 2.0不是升級(jí)是架構(gòu)級(jí)重構(gòu)Spring AI 2.0的發(fā)布標(biāo)志著Java系A(chǔ)I Agent從“能用”走向“好用”。很多人沒(méi)注意到2.0徹底廢棄了1.x時(shí)代的ChatClient單例模式改用Strategy模式解耦現(xiàn)在每個(gè)LLM供應(yīng)商Alibaba、Azure、Ollama都提供獨(dú)立的AutoConfiguration你可以同時(shí)注冊(cè)多個(gè)ChatModel Bean按業(yè)務(wù)場(chǎng)景動(dòng)態(tài)路由。比如我們電商系統(tǒng)里商品推薦用Qwen3.7強(qiáng)推理客服問(wèn)答用Qwen1.5快響應(yīng)庫(kù)存預(yù)警用本地Ollama低延遲全部通過(guò)Qualifier注入Service public class InventoryAgent { Autowired Qualifier(ollama-chat-model) // 本地輕量模型 private ChatModel ollamaModel; Autowired Qualifier(qwen-max-chat-model) // 百煉云端大模型 private ChatModel qwenModel; }更關(guān)鍵的是2.0對(duì)ReAct范式的原生支持。1.x時(shí)代你需要手動(dòng)拼接SystemMessageUserMessageAssistantMessage來(lái)模擬Thought-Action-Observation循環(huán)2.0直接提供ReActChatClient你只需定義Tool集合它自動(dòng)處理循環(huán)邏輯Bean public ReActChatClient reactChatClient(ChatModel chatModel, ListTool tools) { return ReActChatClient.builder() .chatModel(chatModel) .tools(tools) .build(); }內(nèi)部實(shí)現(xiàn)會(huì)自動(dòng)在每次LLM響應(yīng)后解析Action JSON調(diào)用對(duì)應(yīng)Tool將Observation結(jié)果追加到消息歷史——這省去了你手寫(xiě)狀態(tài)機(jī)的80%代碼量。我們實(shí)測(cè)過(guò)同樣一個(gè)“查詢用戶近3個(gè)月訂單并分析退貨率”的Agent2.0版本代碼量比1.x減少63%且可讀性大幅提升業(yè)務(wù)邏輯集中在Tool實(shí)現(xiàn)里而非分散在消息拼接字符串中。2.3 ReAct不是新概念是Java程序員最熟悉的決策模式ReActReasoning Acting常被包裝成AI前沿概念但拆開(kāi)看就是Java工程師天天寫(xiě)的業(yè)務(wù)邏輯。想象一個(gè)典型的電商退款流程// 傳統(tǒng)Java代碼 public RefundResult processRefund(Order order) { // Reasoning判斷是否滿足退款條件 if (!order.isPaid() || order.getStatus() OrderStatus.CANCELLED) { return new RefundResult(false, 訂單未支付或已取消); } // Acting調(diào)用支付網(wǎng)關(guān)退款 PaymentResult paymentResult paymentGateway.refund(order.getPaymentId()); // Observing檢查退款結(jié)果 if (paymentResult.isSuccess()) { updateOrderStatus(order.getId(), OrderStatus.REFUNDED); return new RefundResult(true, 退款成功); } else { log.error(支付網(wǎng)關(guān)退款失敗, paymentResult.getErrorCode()); return new RefundResult(false, 支付網(wǎng)關(guān)異常); } }ReAct Agent只是把這個(gè)模式LLM化LLM負(fù)責(zé)Reasoning生成Thought“需確認(rèn)訂單支付狀態(tài)和庫(kù)存鎖定情況”Java代碼負(fù)責(zé)Acting調(diào)用OrderService.checkPaymentStatus()Observation則由Service返回結(jié)果“訂單已支付庫(kù)存鎖定中”。關(guān)鍵差異在于ReAct把決策權(quán)交給LLM但執(zhí)行權(quán)牢牢掌握在Java手里——這才是企業(yè)級(jí)落地的安全底線。我們所有Agent的Tool都強(qiáng)制要求必須有明確的輸入DTO、輸出DTO、異常碼定義和普通Service接口無(wú)異。比如庫(kù)存查詢ToolTool(check_inventory) public class CheckInventoryTool implements Tool { Override public String invoke(String inputJson) { try { InventoryQuery query JsonUtil.parse(inputJson, InventoryQuery.class); InventoryResult result inventoryService.query(query.getSkuId()); return JsonUtil.toJson(result); // 標(biāo)準(zhǔn)JSON輸出 } catch (Exception e) { return JsonUtil.toJson(new ErrorResult(e.getMessage())); // 統(tǒng)一錯(cuò)誤格式 } } }這種設(shè)計(jì)讓LLM永遠(yuǎn)在“安全沙盒”里思考所有危險(xiǎn)操作如數(shù)據(jù)庫(kù)寫(xiě)入、資金轉(zhuǎn)賬都必須經(jīng)過(guò)Java層校驗(yàn)——既發(fā)揮LLM的推理優(yōu)勢(shì)又守住Java的工程底線。3. 從零搭建生產(chǎn)級(jí)AI Agent四步落地法3.1 環(huán)境準(zhǔn)備避開(kāi)JDK和依賴的三大深坑Java工程師最容易栽在環(huán)境配置上不是因?yàn)閺?fù)雜而是因?yàn)椤疤煜ぁ?。我們踩過(guò)的坑里90%源于對(duì)新舊版本兼容性的誤判。第一個(gè)坑JDK版本。Spring AI 2.0.1要求JDK 17但很多老項(xiàng)目還在用JDK 8。強(qiáng)行升級(jí)會(huì)導(dǎo)致MyBatis 3.4.x的TypeHandler失效——因?yàn)镴DK 17的VarHandle API改變了反射行為。解決方案不是升級(jí)MyBatis而是用Spring AI官方推薦的JDK 17MyBatis 3.5.12組合我們實(shí)測(cè)過(guò)這個(gè)組合下SelectProvider注解能正確解析Lambda表達(dá)式。第二個(gè)坑Lombok和MapStruct沖突。LangChain4j的Message類大量使用Data而MapStruct 1.5.x的Mapper注解在JDK 17下會(huì)和Lombok的Builder產(chǎn)生字節(jié)碼沖突。解決方法是在pom.xml里顯式排除Lombok的lombok-ast依賴dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId exclusions exclusion groupIdorg.projectlombok/groupId artifactIdlombok-ast/artifactId /exclusion /exclusions /dependency第三個(gè)坑最隱蔽SLF4J綁定沖突。Spring AI底層用Logback但很多企業(yè)項(xiàng)目強(qiáng)制使用Log4j2。如果classpath里同時(shí)存在logback-classic.jar和log4j-to-slf4j.jar會(huì)導(dǎo)致LoggerFactory.getLogger()返回null。我們的解法是統(tǒng)一用log4j2添加橋接依賴dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-log4j2/artifactId /dependency dependency groupIdorg.slf4j/groupId artifactIdslf4j-api/artifactId /dependency并確保log4j2.xml里配置Configuration statusWARN Appenders Console nameConsole targetSYSTEM_OUT PatternLayout pattern%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n/ /Console /Appenders Loggers Logger nameorg.springframework.ai levelDEBUG/ Root levelinfo AppenderRef refConsole/ /Root /Loggers /Configuration3.2 核心組件實(shí)現(xiàn)用Java慣用法寫(xiě)Agent3.2.1 Tool設(shè)計(jì)把業(yè)務(wù)服務(wù)變成Agent的“肌肉”Tool不是簡(jiǎn)單封裝API而是要遵循Java服務(wù)的設(shè)計(jì)哲學(xué)。以我們做的“物流軌跡查詢Tool”為例它必須滿足四個(gè)原則冪等性相同參數(shù)多次調(diào)用返回相同結(jié)果、可監(jiān)控暴露調(diào)用耗時(shí)和成功率指標(biāo)、可降級(jí)熔斷后返回緩存數(shù)據(jù)、可追溯記錄完整調(diào)用鏈路。實(shí)現(xiàn)代碼如下Component Tool(query_logistics_track) public class LogisticsTrackTool implements Tool { private final Logger logger LoggerFactory.getLogger(LogisticsTrackTool.class); private final MeterRegistry meterRegistry; // Micrometer指標(biāo)注冊(cè) private final CacheString, TrackResult trackCache; // Caffeine緩存 public LogisticsTrackTool(MeterRegistry meterRegistry, CacheString, TrackResult trackCache) { this.meterRegistry meterRegistry; this.trackCache trackCache; } Override public String invoke(String inputJson) { long startTime System.currentTimeMillis(); try { LogisticsQuery query JsonUtil.parse(inputJson, LogisticsQuery.class); // 緩存穿透防護(hù) String cacheKey query.getExpressNo() _ query.getCompanyCode(); TrackResult cached trackCache.getIfPresent(cacheKey); if (cached ! null) { meterRegistry.counter(tool.logistics.cache.hit).increment(); return JsonUtil.toJson(cached); } // 熔斷器保護(hù) if (!circuitBreaker.tryAcquire()) { logger.warn(Logistics service circuit breaker open, return cached data); return JsonUtil.toJson(TrackResult.empty()); } // 實(shí)際調(diào)用物流API TrackResult result logisticsApiClient.query(query); trackCache.put(cacheKey, result); meterRegistry.counter(tool.logistics.success).increment(); return JsonUtil.toJson(result); } catch (Exception e) { meterRegistry.counter(tool.logistics.error).increment(); logger.error(Logistics query failed, e); return JsonUtil.toJson(new TrackResult(ERROR, e.getMessage())); } finally { meterRegistry.timer(tool.logistics.duration).record(System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS); } } }注意這里沒(méi)有用任何AI框架特有語(yǔ)法全是Spring Boot標(biāo)準(zhǔn)實(shí)踐構(gòu)造器注入、Micrometer指標(biāo)、Caffeine緩存、Resilience4j熔斷——這意味著你的運(yùn)維同學(xué)不用學(xué)新東西就能監(jiān)控這個(gè)Tool的健康度。3.2.2 Prompt工程用Java注解管理提示詞別再把Prompt寫(xiě)死在String里Spring AI 2.0支持PromptTemplate但我們更進(jìn)一步用Java注解實(shí)現(xiàn)提示詞版本管理PromptTemplate( 你是一個(gè)專業(yè)的電商客服Agent請(qǐng)根據(jù)以下信息分析用戶意圖 用戶消息{{userMessage}} 訂單狀態(tài){{orderStatus}} 最近3次對(duì)話{{history}} 請(qǐng)嚴(yán)格按JSON格式輸出 {thought: 你的推理過(guò)程, action: 下一步操作check_order|contact_customer|escalate_to_human, action_input: 操作所需參數(shù)} ) public record CustomerServicePrompt( PromptVariable(userMessage) String userMessage, PromptVariable(orderStatus) String orderStatus, PromptVariable(history) ListString history ) {}編譯時(shí)注解處理器會(huì)生成PromptTemplate實(shí)例運(yùn)行時(shí)自動(dòng)注入變量。好處是提示詞變更無(wú)需重啟應(yīng)用只需修改注解值不同業(yè)務(wù)線可用不同注解CustomerServicePrompt vs FinanceAuditPromptIDE能自動(dòng)提示變量名避免拼寫(xiě)錯(cuò)誤。我們上線后提示詞迭代效率提升5倍且每次變更都有Git提交記錄可追溯。3.2.3 ReAct循環(huán)用State Machine管理Agent生命周期Spring AI的ReActChatClient雖好但企業(yè)級(jí)場(chǎng)景需要更精細(xì)的狀態(tài)控制。我們基于Spring Statemachine實(shí)現(xiàn)自定義ReAct引擎Configuration EnableStateMachineFactory public class AgentStateMachineConfig { Bean public StateMachineAgentState, AgentEvent stateMachine() { StateMachineBuilder.BuilderAgentState, AgentEvent builder StateMachineBuilder.builder(); return builder .configureConfiguration() .withConfiguration() .autoStartup(true) .listener(stateMachineListener()) .and() .configureStates() .withStates() .initial(AgentState.INITIAL) .state(AgentState.REASONING) .state(AgentState.ACTING) .state(AgentState.OBSERVING) .state(AgentState.FINAL) .and() .configureTransitions() .withExternal() .source(AgentState.INITIAL).target(AgentState.REASONING) .event(AgentEvent.START) .and() .withExternal() .source(AgentState.REASONING).target(AgentState.ACTING) .event(AgentEvent.GENERATE_ACTION) .and() .withExternal() .source(AgentState.ACTING).target(AgentState.OBSERVING) .event(AgentEvent.EXECUTE_TOOL) .and() .withExternal() .source(AgentState.OBSERVING).target(AgentState.REASONING) .event(AgentEvent.RECEIVE_OBSERVATION) .action(observationAction()) // 處理觀測(cè)結(jié)果 .and() .withExternal() .source(AgentState.REASONING).target(AgentState.FINAL) .event(AgentEvent.FINISH) .and() .configureConfiguration() .withConfiguration() .machineId(customer-service-agent); } }這樣每個(gè)Agent實(shí)例都有清晰的狀態(tài)流轉(zhuǎn)可以監(jiān)聽(tīng)每個(gè)狀態(tài)進(jìn)入/退出事件做審計(jì)日志、耗時(shí)統(tǒng)計(jì)、異常告警。比如在OBSERVING狀態(tài)退出時(shí)我們記錄private ActionAgentState, AgentEvent observationAction() { return context - { String observation context.getExtendedState().get(observation, String.class); String thought context.getExtendedState().get(thought, String.class); // 寫(xiě)入審計(jì)日志表 auditLogService.save(new AuditLog( context.getMessageHeader().get(traceId), thought, observation, System.currentTimeMillis() - context.getStateMachine().getState().getTimestamp() )); }; }3.3 生產(chǎn)部署讓Agent像普通微服務(wù)一樣穩(wěn)定3.3.1 資源隔離為L(zhǎng)LM調(diào)用分配獨(dú)立線程池千萬(wàn)別讓Agent調(diào)用和業(yè)務(wù)請(qǐng)求共用Tomcat線程池我們吃過(guò)虧一次大促期間Agent批量分析用戶畫(huà)像占滿所有線程導(dǎo)致支付接口超時(shí)。解決方案是創(chuàng)建專用線程池Configuration public class AgentThreadPoolConfig { Bean(agentTaskExecutor) public Executor agentTaskExecutor() { ThreadPoolTaskExecutor executor new ThreadPoolTaskExecutor(); executor.setCorePoolSize(4); // 根據(jù)LLM QPS調(diào)整 executor.setMaxPoolSize(8); executor.setQueueCapacity(100); executor.setThreadNamePrefix(agent-task-); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }所有Agent調(diào)用都用Async標(biāo)注Service public class CustomerServiceAgent { Async(agentTaskExecutor) public CompletableFutureAgentResponse handleRequest(AgentRequest request) { // ReAct循環(huán)執(zhí)行 return CompletableFuture.completedFuture(response); } }配合Spring Boot Actuator可以實(shí)時(shí)監(jiān)控線程池狀態(tài)GET /actuator/metrics/executor.active GET /actuator/metrics/executor.queue3.3.2 Token管理用Java的String操作應(yīng)對(duì)LLM限制Qwen3.7的8192 token限制本質(zhì)是字符串長(zhǎng)度問(wèn)題。我們用Java原生API做預(yù)處理public class TokenTruncator { private static final int MAX_TOKENS 8192; public static String truncateByTokens(String text, int maxTokens) { // 中文按字符數(shù)粗略估算實(shí)際需用tokenizer此處簡(jiǎn)化 int charLimit Math.min(text.length(), maxTokens * 2); // 中文平均2字節(jié)/token if (text.length() charLimit) return text; // 保留關(guān)鍵上下文開(kāi)頭系統(tǒng)提示 結(jié)尾用戶消息 String systemPart extractSystemPart(text); String userPart extractUserPart(text); int remaining charLimit - systemPart.length() - userPart.length(); // 中間內(nèi)容截取保留段落結(jié)構(gòu) String middle text.substring(systemPart.length(), text.length() - userPart.length()); return systemPart truncateMiddle(middle, remaining) userPart; } private static String truncateMiddle(String text, int limit) { if (text.length() limit) return text; int half limit / 2; return text.substring(0, half) [...] text.substring(text.length() - half); } }上線后Agent因token超限導(dǎo)致的500錯(cuò)誤歸零。更重要的是這個(gè)方案不依賴Python tokenizer純Java實(shí)現(xiàn)運(yùn)維同學(xué)能直接看懂邏輯。3.3.3 監(jiān)控告警復(fù)用現(xiàn)有APM體系我們沒(méi)上新監(jiān)控系統(tǒng)而是把Agent指標(biāo)打到SkyWalkingComponent public class AgentTracingAspect { Around(annotation(org.springframework.ai.chat.ChatRequest)) public Object traceAgentCall(ProceedingJoinPoint joinPoint) throws Throwable { String methodName joinPoint.getSignature().getName(); long start System.currentTimeMillis(); try { Object result joinPoint.proceed(); long duration System.currentTimeMillis() - start; // 上報(bào)SkyWalking自定義指標(biāo) CollectorContextHelper.setEntrySpanTag(agent.method, methodName); CollectorContextHelper.setEntrySpanTag(agent.duration, String.valueOf(duration)); return result; } catch (Exception e) { long duration System.currentTimeMillis() - start; CollectorContextHelper.setEntrySpanTag(agent.error, e.getClass().getSimpleName()); throw e; } } }這樣在SkyWalking UI里Agent調(diào)用和普通HTTP接口一樣顯示拓?fù)鋱D、慢SQL、異常堆?!\(yùn)維同學(xué)不需要學(xué)新工具就能定位Agent性能瓶頸。4. 避坑指南Java工程師專屬的12個(gè)實(shí)戰(zhàn)陷阱4.1 常見(jiàn)問(wèn)題速查表問(wèn)題現(xiàn)象根本原因解決方案實(shí)測(cè)耗時(shí)ReActChatClient調(diào)用后卡住無(wú)響應(yīng)LLM響應(yīng)流式傳輸未關(guān)閉連接在application.yml中設(shè)置spring.ai.retry.max-attempts3并配置spring.ai.timeout.read30s2小時(shí)Tool返回JSON含中文亂碼HTTP響應(yīng)頭未指定charset在Tool實(shí)現(xiàn)中顯式設(shè)置response.setContentType(application/json;charsetUTF-8)15分鐘多個(gè)Agent共享同一ChatModel導(dǎo)致token泄露Spring Bean默認(rèn)單例LLM客戶端狀態(tài)未隔離為每個(gè)Agent創(chuàng)建獨(dú)立的ChatModel Bean用Scope(prototype)45分鐘Prometheus指標(biāo)中Agent調(diào)用次數(shù)為0Micrometer Registry未正確注入在Configuration類中添加EnableMeterRegistry并確保MeterRegistryBean被Autowired30分鐘本地Ollama模型啟動(dòng)失敗報(bào)connection refusedDocker Desktop未啟用WSL2后端在Windows設(shè)置中啟用WSL2重啟Docker執(zhí)行ollama serve驗(yàn)證1小時(shí)4.2 獨(dú)家避坑技巧提示Spring AI 2.0.1的ReActChatClient在處理長(zhǎng)文本時(shí)會(huì)因默認(rèn)的StreamingChatClient緩沖區(qū)溢出導(dǎo)致OOM。不要調(diào)大JVM堆內(nèi)存而應(yīng)在配置中禁用流式傳輸spring: ai: chat: streaming: false # 關(guān)鍵避免BufferOverflowError注意LangChain4j的Message類默認(rèn)使用Jackson序列化但某些LLM返回的JSON含特殊字符如\u2028行分隔符會(huì)導(dǎo)致反序列化失敗。解決方案是自定義ObjectMapperBean public ObjectMapper objectMapper() { ObjectMapper mapper new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true); return mapper; }實(shí)操心得別在Agent里直接調(diào)用System.out.println()調(diào)試LLM響應(yīng)是異步流print語(yǔ)句會(huì)打亂JSON結(jié)構(gòu)。正確做法是用log.debug(Agent step: {}, JsonUtil.toJson(stepData))并配置logback的%X{traceId}打印全鏈路ID。4.3 面試高頻題深度解析QSpring AI和LangChain4j的關(guān)系是什么ALangChain4j是基礎(chǔ)協(xié)議層定義了ChatModel、Tool、Message等Java接口Spring AI是工程框架層提供AutoConfiguration、ReActChatClient、PromptTemplate等開(kāi)箱即用組件。類比關(guān)系LangChain4j ≈ JDBC規(guī)范Spring AI ≈ Spring JDBC Template。Q如何保證Agent的可測(cè)試性A三步走1) Tool層用Mockito模擬外部API2) ReAct循環(huán)用ReActChatClient的setChatModel()注入MockChatModel3) 業(yè)務(wù)邏輯用JUnit 5的Nested測(cè)試不同ReAct路徑。我們團(tuán)隊(duì)要求每個(gè)Agent必須有覆蓋Thought/Action/Observation全流程的測(cè)試用例。QJava Agent和Rust Agent的核心差異在哪A不是性能差異而是工程范式差異。Rust Agent追求極致性能如async-std無(wú)棧協(xié)程但犧牲了Java的生態(tài)紅利Spring Security權(quán)限控制、MyBatis事務(wù)管理、SkyWalking全鏈路追蹤。在企業(yè)場(chǎng)景可維護(hù)性比單機(jī)QPS重要10倍。5. 后續(xù)演進(jìn)從單Agent到Agent集群的平滑升級(jí)5.1 多路召回用Java的Collection API實(shí)現(xiàn)LangChain4j的多路召回常被神化其實(shí)質(zhì)就是Java的并行Stream處理。我們做的商品推薦Agent同時(shí)調(diào)用三個(gè)數(shù)據(jù)源public ListRecommendItem multiSourceRecall(String userId) { return Stream.of( // 模型召回調(diào)用Qwen3.7生成向量 CompletableFuture.supplyAsync(() - vectorRecall(userId), agentTaskExecutor), // 規(guī)則召回基于用戶歷史行為的硬規(guī)則 CompletableFuture.supplyAsync(() - ruleRecall(userId), agentTaskExecutor), // 熱門(mén)召回Redis緩存的實(shí)時(shí)熱門(mén)商品 CompletableFuture.supplyAsync(() - hotRecall(userId), agentTaskExecutor) ) .map(CompletableFuture::join) // 等待所有召回完成 .flatMap(List::stream) .distinct() // 去重 .sorted(Comparator.comparing(RecommendItem::getScore).reversed()) // 按分?jǐn)?shù)排序 .limit(20) // 取Top20 .collect(Collectors.toList()); }關(guān)鍵點(diǎn)在于每個(gè)召回源都用獨(dú)立線程池避免互相阻塞CompletableFuture.join()保證超時(shí)控制最終用Java 8 Stream API做融合——沒(méi)有引入任何AI框架特有概念全是Java工程師的日常操作。5.2 Agent協(xié)作用Spring Cloud Stream解耦當(dāng)單Agent能力不足時(shí)我們用消息隊(duì)列構(gòu)建Agent網(wǎng)絡(luò)。比如風(fēng)控Agent檢測(cè)到高風(fēng)險(xiǎn)訂單發(fā)消息到risk-alert-topic審計(jì)Agent和通知Agent各自訂閱Service public class RiskAlertConsumer { StreamListener(target risk-alert-topic) public void handleRiskAlert(RiskAlert alert) { // 審計(jì)Agent執(zhí)行合規(guī)檢查 auditService.checkCompliance(alert.getOrderNo()); // 通知Agent發(fā)送預(yù)警短信 notificationService.sendAlert(alert.getPhone()); } }這樣每個(gè)Agent職責(zé)單一可獨(dú)立擴(kuò)縮容故障隔離——這才是真正的微服務(wù)思維而不是把所有邏輯塞進(jìn)一個(gè)ReAct循環(huán)。5.3 持續(xù)學(xué)習(xí)用Java的ClassLoader熱更新Prompt我們把Prompt模板放在數(shù)據(jù)庫(kù)里用定時(shí)任務(wù)掃描更新Component public class PromptHotReload { Scheduled(fixedRate 300000) // 5分鐘檢查一次 public void reloadPrompts() { ListPromptEntity updated promptRepository.findUpdatedSince(lastCheckTime); for (PromptEntity entity : updated) { // 動(dòng)態(tài)編譯新的PromptTemplate類 Class? compiledClass DynamicCompiler.compile(entity.getTemplateCode()); // 替換Spring容器中的Bean applicationContext.getBeanFactory().destroySingleton(entity.getBeanName()); applicationContext.getBeanFactory().registerSingleton(entity.getBeanName(), compiledClass.newInstance()); } lastCheckTime Instant.now(); } }上線后運(yùn)營(yíng)同學(xué)改一句提示詞30秒內(nèi)生效無(wú)需發(fā)版——這才是Java工程師該有的敏捷交付體驗(yàn)。我在實(shí)際項(xiàng)目中發(fā)現(xiàn)最成功的Java系A(chǔ)I Agent往往不是技術(shù)最炫的而是把Spring Boot最佳實(shí)踐貫徹到底的用Transactional保證LLM調(diào)用的冪等性用Cacheable緩存重復(fù)的Observation用Scheduled做Agent健康檢查。AI不是顛覆Java而是讓Java工程師十年磨一劍的工程能力在新戰(zhàn)場(chǎng)煥發(fā)第二春。