当前位置: 首页 > article >正文

Spring Boot项目里,我是怎么把文心一言API集成进去的(附完整代码)

Spring Boot项目中集成文心一言API的实战指南最近在开发一个需要AI对话功能的Spring Boot应用时我选择了百度的文心一言作为后端引擎。整个过程从申请API权限到最终实现流式响应踩了不少坑也积累了一些经验。本文将分享如何在Spring Boot项目中优雅地集成文心一言API包括配置管理、服务封装和性能优化等实战细节。1. 环境准备与权限申请在开始编码前我们需要完成两项准备工作创建文心一言应用和配置Spring Boot项目。首先访问百度智能云平台找到文心千帆大模型服务。创建应用后会获得API Key和Secret Key这两个凭证将用于后续的接口认证。建议将这些敏感信息存储在环境变量中而不是直接硬编码在项目里。对于Spring Boot项目基础依赖如下dependencies dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdcom.squareup.okhttp3/groupId artifactIdokhttp/artifactId version4.9.3/version /dependency dependency groupIdcom.fasterxml.jackson.core/groupId artifactIdjackson-databind/artifactId /dependency /dependencies关键配置参数建议放在application.yml中wenxin: api: key: ${WENXIN_API_KEY} secret: ${WENXIN_API_SECRET} base-url: https://aip.baidubce.com2. 核心服务层实现我们将创建一个WenxinService来处理所有与文心一言API的交互。这个服务需要处理认证令牌的获取和管理。首先定义配置类自动注入参数ConfigurationProperties(prefix wenxin.api) Getter Setter public class WenxinProperties { private String key; private String secret; private String baseUrl; }然后实现核心服务类Service RequiredArgsConstructor public class WenxinService { private final WenxinProperties properties; private final OkHttpClient httpClient; private String cachedToken; private Instant tokenExpireTime; public String getToken() { if (cachedToken ! null Instant.now().isBefore(tokenExpireTime)) { return cachedToken; } HttpUrl url HttpUrl.parse(properties.getBaseUrl() /oauth/2.0/token) .newBuilder() .addQueryParameter(grant_type, client_credentials) .addQueryParameter(client_id, properties.getKey()) .addQueryParameter(client_secret, properties.getSecret()) .build(); Request request new Request.Builder() .url(url) .build(); try (Response response httpClient.newCall(request).execute()) { JsonNode root objectMapper.readTree(response.body().string()); cachedToken root.path(access_token).asText(); int expiresIn root.path(expires_in).asInt(); tokenExpireTime Instant.now().plusSeconds(expiresIn - 300); // 提前5分钟刷新 return cachedToken; } catch (IOException e) { throw new RuntimeException(Failed to get access token, e); } } }3. 实现同步与异步调用文心一言API支持两种调用方式同步阻塞式和异步流式。我们先实现同步调用public String sendMessageSync(ListChatMessage messages) { String token getToken(); HttpUrl url HttpUrl.parse(properties.getBaseUrl() /rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant) .newBuilder() .addQueryParameter(access_token, token) .build(); MapString, Object body Map.of( messages, messages, stream, false ); Request request new Request.Builder() .url(url) .post(RequestBody.create( objectMapper.writeValueAsString(body), MediaType.parse(application/json) )) .build(); try (Response response httpClient.newCall(request).execute()) { JsonNode root objectMapper.readTree(response.body().string()); return root.path(result).asText(); } catch (IOException e) { throw new RuntimeException(API call failed, e); } }对于需要实时交互的场景流式调用能显著提升用户体验public void sendMessageStream(ListChatMessage messages, ConsumerString callback) { String token getToken(); HttpUrl url HttpUrl.parse(properties.getBaseUrl() /rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant) .newBuilder() .addQueryParameter(access_token, token) .build(); MapString, Object body Map.of( messages, messages, stream, true ); Request request new Request.Builder() .url(url) .post(RequestBody.create( objectMapper.writeValueAsString(body), MediaType.parse(application/json) )) .build(); EventSource.Factory factory EventSources.createFactory(httpClient); factory.newEventSource(request, new EventSourceListener() { Override public void onEvent(EventSource eventSource, String id, String type, String data) { try { JsonNode node objectMapper.readTree(data); callback.accept(node.path(result).asText()); } catch (JsonProcessingException e) { // 错误处理 } } Override public void onFailure(EventSource eventSource, Throwable t, Response response) { // 错误处理 } }); }4. 性能优化与最佳实践在实际使用中我们发现几个可以显著提升性能和稳定性的优化点连接池配置OkHttpClient默认连接池可能不适合高并发场景Bean public OkHttpClient okHttpClient() { return new OkHttpClient.Builder() .connectionPool(new ConnectionPool(20, 5, TimeUnit.MINUTES)) .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build(); }重试机制对于临时性网络问题可以自动重试public class RetryInterceptor implements Interceptor { Override public Response intercept(Chain chain) throws IOException { Request request chain.request(); Response response null; IOException exception null; for (int i 0; i 3; i) { try { response chain.proceed(request); if (response.isSuccessful()) { return response; } } catch (IOException e) { exception e; } try { Thread.sleep(1000 * (i 1)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(Interrupted during retry, e); } } if (response ! null) { throw new IOException(API request failed after retries: response.code()); } throw exception; } }限流控制防止突发流量导致服务不可用Bean public RateLimiter wenxinRateLimiter() { return RateLimiter.create(5); // 每秒5个请求 } Service public class RateLimitedWenxinService { private final WenxinService wenxinService; private final RateLimiter rateLimiter; public String sendMessageWithRateLimit(ListChatMessage messages) { rateLimiter.acquire(); return wenxinService.sendMessageSync(messages); } }5. 异常处理与监控完善的异常处理能显著提升系统稳定性。我们定义了自定义异常public class WenxinException extends RuntimeException { public enum ErrorType { AUTH_FAILURE, RATE_LIMIT, NETWORK_ERROR, API_ERROR } private final ErrorType errorType; public WenxinException(ErrorType errorType, String message) { super(message); this.errorType errorType; } // 省略getter方法 }同时集成Spring Boot的Actuator进行监控management: endpoints: web: exposure: include: health,metrics,prometheus metrics: tags: application: ${spring.application.name}自定义指标监控API调用Bean public MeterRegistryCustomizerMeterRegistry metricsCommonTags() { return registry - registry.config().commonTags( application, ai-service, region, System.getenv().getOrDefault(REGION, unknown) ); } Service public class MonitoredWenxinService { private final WenxinService delegate; private final Counter successCounter; private final Counter failureCounter; private final Timer apiTimer; public MonitoredWenxinService(WenxinService delegate, MeterRegistry registry) { this.delegate delegate; this.successCounter registry.counter(wenxin.api.calls, status, success); this.failureCounter registry.counter(wenxin.api.calls, status, failure); this.apiTimer registry.timer(wenxin.api.latency); } public String sendMessageWithMonitoring(ListChatMessage messages) { return apiTimer.record(() - { try { String result delegate.sendMessageSync(messages); successCounter.increment(); return result; } catch (Exception e) { failureCounter.increment(); throw e; } }); } }6. 实际应用案例最后分享一个在客服系统中集成的实际案例。我们创建了一个RestController来处理用户咨询RestController RequestMapping(/api/chat) RequiredArgsConstructor public class ChatController { private final WenxinService wenxinService; PostMapping public ResponseEntityChatResponse chat(RequestBody ChatRequest request) { ListChatMessage messages request.getMessages(); String response wenxinService.sendMessageSync(messages); return ResponseEntity.ok(new ChatResponse(response)); } GetMapping(/stream) public SseEmitter streamChat(RequestParam String question) { SseEmitter emitter new SseEmitter(30_000L); ListChatMessage messages List.of( new ChatMessage(user, question) ); wenxinService.sendMessageStream(messages, chunk - { try { emitter.send(SseEmitter.event() .data(chunk) .id(UUID.randomUUID().toString())); } catch (IOException e) { emitter.completeWithError(e); } }); return emitter; } }对于前端集成流式接口可以这样使用const eventSource new EventSource(/api/chat/stream?question encodeURIComponent(question)); let fullResponse ; eventSource.onmessage (event) { fullResponse event.data; updateUI(fullResponse); }; eventSource.onerror () { eventSource.close(); };

相关文章:

Spring Boot项目里,我是怎么把文心一言API集成进去的(附完整代码)

Spring Boot项目中集成文心一言API的实战指南 最近在开发一个需要AI对话功能的Spring Boot应用时,我选择了百度的文心一言作为后端引擎。整个过程从申请API权限到最终实现流式响应,踩了不少坑也积累了一些经验。本文将分享如何在Spring Boot项目中优雅地…...

Windows Cleaner深度解析:从C盘爆红到系统性能全面优化的完整方案

Windows Cleaner深度解析:从C盘爆红到系统性能全面优化的完整方案 【免费下载链接】WindowsCleaner Windows Cleaner——专治C盘爆红及各种不服! 项目地址: https://gitcode.com/gh_mirrors/wi/WindowsCleaner Windows Cleaner是一款完全免费开源…...

CTF实战:手把手教你用phar伪协议绕过NSS靶场文件上传限制

CTF实战:手把手教你用phar伪协议绕过NSS靶场文件上传限制 在网络安全竞赛和渗透测试中,文件上传漏洞一直是高频考点。今天我们将深入探讨如何利用PHP的phar伪协议,绕过NSSCTF平台"bingdundun"题目的文件上传限制,实现远…...

Spring Cloud微服务里,如何用XXL-JOB搞定订单15分钟未支付自动关闭?

Spring Cloud微服务中基于XXL-JOB的订单超时自动关闭实战方案 电商平台的订单超时自动关闭是一个典型的高并发业务场景。想象一下,当用户下单后未支付,系统需要在15分钟后自动释放库存并关闭订单。传统做法可能采用数据库轮询或延迟队列,但在…...

LVGL事件处理实战:从按钮点击到复杂手势,手把手教你写响应式UI回调

LVGL事件处理实战:从按钮点击到复杂手势,手把手教你写响应式UI回调 在嵌入式系统开发中,用户界面的交互体验往往决定了产品的成败。LVGL作为轻量级通用图形库,其事件处理机制是构建动态交互的核心。不同于简单的回调函数绑定&…...

从主题到视频:Pixelle-Video如何用AI重构你的内容创作流程

从主题到视频:Pixelle-Video如何用AI重构你的内容创作流程 【免费下载链接】Pixelle-Video 🚀 AI 全自动短视频引擎 | AI Fully Automated Short Video Engine 项目地址: https://gitcode.com/GitHub_Trending/pi/Pixelle-Video 想象一下&#xf…...

Windows流媒体服务器终极指南:5分钟部署SRS高性能视频传输平台

Windows流媒体服务器终极指南:5分钟部署SRS高性能视频传输平台 【免费下载链接】srs-windows 项目地址: https://gitcode.com/gh_mirrors/sr/srs-windows 在Windows平台上快速搭建专业级流媒体服务器,SRS(Simple Realtime Server&…...

GASShooter伤害计算与GameplayEffectContext:自定义伤害类型与爆头机制终极指南 [特殊字符]

GASShooter伤害计算与GameplayEffectContext:自定义伤害类型与爆头机制终极指南 🎯 【免费下载链接】GASShooter Advanced FPS/TPS Sample Project for Unreal Engine 4s GameplayAbilitySystem plugin 项目地址: https://gitcode.com/gh_mirrors/ga/G…...

如何快速搭建Windows虚拟路由器:VirtualRouter完整使用指南

如何快速搭建Windows虚拟路由器:VirtualRouter完整使用指南 【免费下载链接】VirtualRouter Wifi Hotspot for Windows computers (Windows 7, 8.x, Server 2012 and newer!) 项目地址: https://gitcode.com/gh_mirrors/vi/VirtualRouter VirtualRouter是一款…...

展锐RM500U 5G CPE固件升级避坑指南:为什么你的QFlash总卡在‘开始下载’?

展锐RM500U 5G CPE固件升级疑难解析:从QFlash卡顿到完美升级的实战手册 当你的展锐RM500U 5G CPE设备需要固件升级时,QFlash工具本应是简单高效的解决方案。然而,许多用户在点击"Start"按钮后,却遭遇了进度条停滞不前的…...

如何获取VMware Workstation Pro 17免费许可证密钥:完整实践指南

如何获取VMware Workstation Pro 17免费许可证密钥:完整实践指南 【免费下载链接】VMware-Workstation-Pro-17-Licence-Keys Free VMware Workstation Pro 17 full license keys. Weve meticulously organized thousands of keys, catering to all major versions o…...

如何利用LayerPlayer快速掌握iOS动画开发技巧

如何利用LayerPlayer快速掌握iOS动画开发技巧 【免费下载链接】LayerPlayer Layer Player explores the capabilities of Apples Core Animation API 项目地址: https://gitcode.com/gh_mirrors/la/LayerPlayer LayerPlayer是一款专注于探索Apple Core Animation API功能…...

3个实用技巧:用SMUDebugTool解决AMD Ryzen常见硬件问题

3个实用技巧:用SMUDebugTool解决AMD Ryzen常见硬件问题 【免费下载链接】SMUDebugTool A dedicated tool to help write/read various parameters of Ryzen-based systems, such as manual overclock, SMU, PCI, CPUID, MSR and Power Table. 项目地址: https://g…...

June主题定制教程:从模板修改到样式定制的完整解决方案

June主题定制教程:从模板修改到样式定制的完整解决方案 【免费下载链接】june June is a forum (Deprecated) 项目地址: https://gitcode.com/gh_mirrors/ju/june June是一款开源论坛项目,通过本教程你将学习如何轻松定制June论坛的主题外观&…...

终极指南:如何用罗技鼠标宏实现PUBG完美压枪控制

终极指南:如何用罗技鼠标宏实现PUBG完美压枪控制 【免费下载链接】logitech-pubg PUBG no recoil script for Logitech gaming mouse / 绝地求生 罗技 鼠标宏 项目地址: https://gitcode.com/gh_mirrors/lo/logitech-pubg 还在为《绝地求生》中难以驾驭的武器…...

城通网盘解析工具:3分钟获取直连地址的完整高效解决方案

城通网盘解析工具:3分钟获取直连地址的完整高效解决方案 【免费下载链接】ctfileGet 获取城通网盘一次性直连地址 项目地址: https://gitcode.com/gh_mirrors/ct/ctfileGet 城通网盘解析工具 ctfileGet 是一款专为破解城通网盘下载限制而设计的开源工具&…...

VMware Workstation Pro 17 免费许可证密钥终极指南:快速获取与完整安装教程

VMware Workstation Pro 17 免费许可证密钥终极指南:快速获取与完整安装教程 【免费下载链接】VMware-Workstation-Pro-17-Licence-Keys Free VMware Workstation Pro 17 full license keys. Weve meticulously organized thousands of keys, catering to all major…...

从红宝石到光纤:固体激光器家族里,谁才是工业加工界的‘六边形战士’?

从红宝石到光纤:固体激光器家族里,谁才是工业加工界的‘六边形战士’? 在金属切割车间里,激光束正以毫米级精度划过不锈钢板;精密电子产线上,纳米级激光打标机为电路板刻印追溯码;汽车焊接工段…...

为什么你的PS手柄在Windows上无法畅玩游戏?3步解锁完美兼容方案

为什么你的PS手柄在Windows上无法畅玩游戏?3步解锁完美兼容方案 【免费下载链接】DS4Windows Like those other ds4tools, but sexier 项目地址: https://gitcode.com/gh_mirrors/ds/DS4Windows 你是否曾经兴奋地想在PC上使用心爱的PlayStation手柄&#xff…...

别再死记硬背了!用COMSOL 5.6搞定声学建模,从房间特征频率到完美匹配层(PML)实战避坑

别再死记硬背了!用COMSOL 5.6搞定声学建模,从房间特征频率到完美匹配层(PML)实战避坑 声学建模在工程应用中越来越重要,无论是建筑声学设计、噪声控制还是医疗超声设备开发,都需要精确的声场模拟。但对于初…...

旧安卓手机别扔!用Termux+LXC把它变成一台Ubuntu Docker服务器(保姆级避坑指南)

旧安卓设备重生指南:打造低功耗Ubuntu容器服务器的完整方案 你是否曾为抽屉里那台退役的安卓手机感到惋惜?当旗舰机型沦为电子垃圾时,其实它们潜藏的算力足以支撑个人开发环境、轻量级服务甚至家庭自动化中枢。本文将揭示如何通过Termux与LXC…...

JMeter临界部分控制器正确用法与避坑指南

1. 为什么“临界部分控制器”是压测中真正卡住团队的隐形瓶颈很多人第一次在JMeter里看到临界部分控制器(Critical Section Controller),第一反应是:“这不就是个带锁的逻辑块?加个锁而已,能有多复杂&#…...

Selenium自动化绕过反爬:彻底清除webdriver指纹的三层策略

1. 为什么“移除 webdriver 标志”成了自动化测试与爬虫绕过的第一道门槛 你有没有遇到过这样的情况:用 Selenium 写好了一套完整的电商比价脚本,本地跑得丝滑流畅,一上服务器或换台新机器就频繁触发验证码,甚至直接返回 403&…...

深度掌握AMD Ryzen性能调优:SMUDebugTool硬件调试终极指南

深度掌握AMD Ryzen性能调优:SMUDebugTool硬件调试终极指南 【免费下载链接】SMUDebugTool A dedicated tool to help write/read various parameters of Ryzen-based systems, such as manual overclock, SMU, PCI, CPUID, MSR and Power Table. 项目地址: https:…...

哔哩漫游X:全面解锁B站功能的终极ReVanced增强模块

哔哩漫游X:全面解锁B站功能的终极ReVanced增强模块 【免费下载链接】BiliRoamingX-integrations BiliRoamingX integrations and patches powered by ReVanced. 项目地址: https://gitcode.com/gh_mirrors/bi/BiliRoamingX-integrations B站作为中国最大的视…...

如何通过Marlin固件配置解决3D打印常见问题:终极完整指南

如何通过Marlin固件配置解决3D打印常见问题:终极完整指南 【免费下载链接】Marlin Marlin is a firmware for RepRap 3D printers optimized for both 8 and 32 bit microcontrollers. Marlin supports all common platforms. Many commercial 3D printers come wit…...

3步快速上手:AMD Ryzen性能调试工具SMUDebugTool完全指南

3步快速上手:AMD Ryzen性能调试工具SMUDebugTool完全指南 【免费下载链接】SMUDebugTool A dedicated tool to help write/read various parameters of Ryzen-based systems, such as manual overclock, SMU, PCI, CPUID, MSR and Power Table. 项目地址: https:/…...

GitHub中文界面终极指南:免费脚本让英文GitHub秒变中文

GitHub中文界面终极指南:免费脚本让英文GitHub秒变中文 【免费下载链接】github-chinese GitHub 汉化插件,GitHub 中文化界面。 (GitHub Translation To Chinese) 项目地址: https://gitcode.com/gh_mirrors/gi/github-chinese 还在为GitHub全英文…...

智慧树自动刷课插件终极指南:3步安装教程,彻底告别手动刷课烦恼!

智慧树自动刷课插件终极指南:3步安装教程,彻底告别手动刷课烦恼! 【免费下载链接】zhihuishu 智慧树刷课插件,自动播放下一集、1.5倍速度、无声 项目地址: https://gitcode.com/gh_mirrors/zh/zhihuishu 还在为智慧树平台的…...

从一次PR被拒说起:我是如何用Git Upstream优雅同步Gitee Fork仓库的

从一次PR被拒说起:我是如何用Git Upstream优雅同步Gitee Fork仓库的 那天下午,当我满怀期待地打开Gitee通知,看到的却是项目维护者冰冷的回复:"PR存在大量冲突,请先同步最新代码"。作为一个刚接触开源贡献的…...