尧图网络科技YAOTU DIGITAL 获取报价
获取报价
首页 / 资讯中心 / 文章详情

使用 AWS SDK for Java v2 构建多语言 Amazon Lex 聊天机器人并集成到 Spring Boot 应用

发布时间:2026/9/25 17:02:20

资讯中心
01
ARTICLE

使用 AWS SDK for Java v2 构建多语言 Amazon Lex 聊天机器人并集成到 Spring Boot 应用

使用 AWS SDK for Java v2 构建多语言 Amazon Lex 聊天机器人并集成到 Spring Boot 应用
示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载导读本教程基于当前仓库 javav2/usecases/creating_lex_chatbot 的完整示例讲解如何用 AWS SDK for Java v2 构建一个支持多种语言的 Amazon Lex 聊天机器人并把它集成进 Spring Boot Web 应用。整个方案串起 Amazon Lex、Amazon Comprehend、Amazon Translate 三项 AWS 服务先识别用户输入语言再翻译为英文交给 Lex 对话最后把机器人的英文回复翻译回用户的原语言。读完本文你将掌握从控制台创建 Lex 机器人、搭建 Spring Boot 项目、编写核心 Java 类到前端页面联调的全流程实战技能。应用场景与架构总览Amazon Lex 聊天机器人能让网站访客以在线对话的方式完成业务交互而无须接触真人客服。本示例中的机器人基于 Lex 官方BookTrip蓝图可以完成“预订酒店房间”这类多轮对话机器人会依次询问入住城市、入住日期、房间类型等槽位Slot信息。该方案与普通单语聊天机器人的关键区别在于多语言处理流水线其核心调用链如下对应源码 LexService.java语言识别调用 Amazon Comprehend 的detectDominantLanguage返回输入文本的语言代码如法语返回fr、意大利语返回it原文转英若语言不是en调用 Amazon Translate 的translateText把用户输入翻译成英文机器人对话把英文文本交给LexRuntimeClient.postText由 Amazon Lex 返回英文回复回复回译若原始语言不是en再调用 Amazon Translate 把英文回复翻译回用户语言并返回给前端。从仓库结构看整个示例由 Spring Boot 的 Web 层Controller Thymeleaf 模板与 AWS 服务调用层LexService两部分组成职责划分清晰。下图展示了实际运行效果——访客用非英语提问机器人同样以该语言回复环境准备Prerequisites开始动手前需要准备以下环境一个有效的AWS 账户一个 Java IDE本教程使用IntelliJ IDEAJava JDK 17Maven 3.6 或更高版本。几点重要提醒本示例涉及的 AWS 服务属于 AWS Free Tier 免费套餐范畴代码并未在全部 AWS 区域测试过部分服务仅在特定区域可用示例代码固定使用us-east-1请参考 AWS Regional Services运行本教程会产生 AWS 费用教程结束后请务必清理所有创建的资源避免持续计费。在 AWS 管理控制台创建 Amazon Lex 机器人第一步是在 AWS 管理控制台创建一个 Lex 机器人这里直接使用 Amazon Lex 提供的BookTrip蓝图登录 AWS 管理控制台打开 Amazon Lex 控制台https://console.aws.amazon.com/lex/在 Bots 页面选择Create选择BookTrip蓝图保留默认机器人名称BookTrip如下图所示控制台会预置好意图Intent、提示语、槽位和 fulfillment 逻辑等核心配置保持默认设置并选择Create在编辑器Editor选项卡中查看预配置意图的细节在测试窗口中测试机器人输入I want to book a hotel room验证多轮对话流程选择Publish发布机器人并指定一个别名alias——这个别名在 Java 代码中会用到。注意在 Java 代码中必须引用机器人名称bot name和机器人别名bot alias二者是PostTextRequest的必填参数。创建名为 SpringChatbot 的 IntelliJ 项目在 IntelliJ IDE 中新建一个 Maven 项目用于承载承载聊天机器人的 Web 站点选择File → New → Project在 New Project 对话框中选择Maven选择Next在GroupId中填入spring-aws在ArtifactId中填入SpringChatbot依次选择Next → Finish。完成后即得到一个名为SpringChatbot的新项目其pom.xml应与本仓库中的 pom.xml 保持一致。配置 POM 依赖项目的pom.xml是本示例的关键构建配置它通过 Spring Boot BOM 管理依赖并引入lexruntime、translate、comprehend三个 AWS SDK 模块。完整内容如下?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion groupIdSpringChatbot/groupId artifactIdSpringChatbot/artifactId version1.0-SNAPSHOT/version parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version2.2.5.RELEASE/version relativePath/ /parent properties project.build.sourceEncodingUTF-8/project.build.sourceEncoding java.version17/java.version maven.compiler.target17/maven.compiler.target maven.compiler.source17/maven.compiler.source /properties dependencyManagement dependencies dependency groupIdsoftware.amazon.awssdk/groupId artifactIdbom/artifactId version2.21.20/version typepom/type scopeimport/scope /dependency /dependencies /dependencyManagement dependencies dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-thymeleaf/artifactId /dependency dependency groupIdsoftware.amazon.awssdk/groupId artifactIdlexruntime/artifactId /dependency dependency groupIdsoftware.amazon.awssdk/groupId artifactIdtranslate/artifactId /dependency dependency groupIdsoftware.amazon.awssdk/groupId artifactIdcomprehend/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-test/artifactId scopetest/scope exclusions exclusion groupIdorg.junit.vintage/groupId artifactIdjunit-vintage-engine/artifactId /exclusion /exclusions /dependency /dependencies build plugins plugin groupIdorg.springframework.boot/groupId artifactIdspring-boot-maven-plugin/artifactId /plugin /plugins /build /project依赖说明spring-boot-starter-web / spring-boot-starter-thymeleaf提供 Spring MVC 控制器与 Thymeleaf 视图渲染能力lexruntimeAWS SDK for Java v2 的 Amazon Lex 运行时客户端用于postText对话调用translateAmazon Translate 客户端承担“转英 / 回译”两个方向的文本翻译comprehendAmazon Comprehend 客户端用于detectDominantLanguage语言识别三个 AWS 模块的版本统一由aws-sdk-java BOMBill of Materials版本 2.21.20在dependencyManagement中集中管理无需逐个指定版本。创建 Java 类在main/java目录下创建包com.aws.spring所有 Java 文件都放在该包中共三个类类名职责BotExampleSpring Boot 应用的主启动类BotController处理 HTTP 请求的 Spring MVC 控制器LexService使用 AWS SDK for Java v2 调用 AWS 服务完成核心业务逻辑这三个类的源码分别位于仓库 BotExample.java、BotController.java 和 LexService.java。BotExampleSpring Boot 启动类package com.aws.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; SpringBootApplication public class BotExample { public static void main(String[] args) { SpringApplication.run(BotExample.class, args); } }SpringBootApplication开启组件扫描与自动配置main方法把BotExample作为入口类启动内嵌 Web 服务器。BotControllerHTTP 请求入口package com.aws.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; Controller public class BotController { Autowired LexService lex; GetMapping(/) public String greetingForm(Model model) { return index; } // Handles a string posted from the client. RequestMapping(value /text, method RequestMethod.POST) ResponseBody String addItems(HttpServletRequest request, HttpServletResponse response) { String text request.getParameter(text); String message lex.getText(text); return message; } }控制器定义了两个端点GET /渲染index视图Thymeleaf 模板即聊天界面首页POST /text接收前端通过表单参数text提交的用户输入调用LexService.getText处理并以字符串形式ResponseBody返回机器人的回复。从源码结构看前端与后端通过这一轻量接口完成异步对话无需 WebSocket 等复杂机制。LexService多语言对话核心逻辑LexService是整个示例的核心类它把所有来自客户端的文本统一交给getText方法处理完整源码如下package com.aws.spring; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lexruntime.LexRuntimeClient; import org.springframework.stereotype.Component; import software.amazon.awssdk.services.lexruntime.model.LexRuntimeException; import software.amazon.awssdk.services.lexruntime.model.PostTextRequest; import software.amazon.awssdk.services.comprehend.ComprehendClient; import software.amazon.awssdk.services.comprehend.model.ComprehendException; import software.amazon.awssdk.services.comprehend.model.DetectDominantLanguageRequest; import software.amazon.awssdk.services.comprehend.model.DetectDominantLanguageResponse; import software.amazon.awssdk.services.comprehend.model.DominantLanguage; import software.amazon.awssdk.services.translate.TranslateClient; import software.amazon.awssdk.services.translate.model.TranslateTextRequest; import software.amazon.awssdk.services.translate.model.TranslateTextResponse; import software.amazon.awssdk.services.translate.model.TranslateException; import java.util.*; import software.amazon.awssdk.services.lexruntime.model.PostTextResponse; Component public class LexService { public String getText(String text) { Region region Region.US_EAST_1; LexRuntimeClient lexRuntimeClient LexRuntimeClient.builder() .region(region) .build(); String engMessage ; try { // Need to determine the language. String lanCode DetectLanguage(text); // If the lanCode is NOT Eng - then we need to translate the message to English to pass to Amazon Lex. if (lanCode.compareTo(en) ! 0) engMessage textTranslateToEn(lanCode, text); else engMessage text; String userId chatbot-demo; MapString, String sessionAttributes new HashMap(); PostTextRequest textRequest PostTextRequest.builder() .botName(BookTrip) .botAlias(ENTER YOUR ALIAS) .inputText(engMessage) .userId(userId) .sessionAttributes(sessionAttributes) .build(); PostTextResponse textResponse lexRuntimeClient.postText(textRequest); String message textResponse.message(); // If not EN, we need to translate the text back String outputText ; if (lanCode.compareTo(en) ! 0) outputText textTranslateFromEn(lanCode, message); else outputText message; return outputText; } catch (LexRuntimeException e) { System.err.println(e.getMessage()); System.exit(1); } return ; } private String DetectLanguage(String text) { Region region Region.US_EAST_1; ComprehendClient comClient ComprehendClient.builder() .region(region) .build(); try { String lanCode ; DetectDominantLanguageRequest request DetectDominantLanguageRequest.builder() .text(text) .build(); DetectDominantLanguageResponse resp comClient.detectDominantLanguage(request); ListDominantLanguage allLanList resp.languages(); IteratorDominantLanguage lanIterator allLanList.iterator(); while (lanIterator.hasNext()) { DominantLanguage lang lanIterator.next(); lanCode lang.languageCode(); } return lanCode; } catch (ComprehendException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ; } public String textTranslateToEn(String lanCode, String text) { Region region Region.US_EAST_1; TranslateClient translateClient TranslateClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(region) .build(); try { TranslateTextRequest textRequest TranslateTextRequest.builder() .sourceLanguageCode(lanCode) .targetLanguageCode(en) .text(text) .build(); TranslateTextResponse textResponse translateClient.translateText(textRequest); return textResponse.translatedText(); } catch (TranslateException e) { System.err.println(e.getMessage()); System.exit(1); } return ; } public String textTranslateFromEn(String lanCode, String text) { Region region Region.US_EAST_1; TranslateClient translateClient TranslateClient.builder() .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .region(region) .build(); try { TranslateTextRequest textRequest TranslateTextRequest.builder() .sourceLanguageCode(en) .targetLanguageCode(lanCode) .text(text) .build(); TranslateTextResponse textResponse translateClient.translateText(textRequest); return textResponse.translatedText(); } catch (TranslateException e) { System.err.println(e.getMessage()); System.exit(1); } return ; } }getText主流程编排getText是整个多语言方案的“编排器”执行顺序如下构建LexRuntimeClient区域固定为US_EAST_1调用DetectLanguage(text)识别语言代码lanCode若lanCode不是en调用textTranslateToEn将输入翻译成英文engMessage否则直接使用原文构造PostTextRequest其中botName固定为BookTrip、botAlias使用你在发布机器人时指定的别名、userId为会话标识示例中固定为chatbot-demo、sessionAttributes用于跨轮对话传递槽位上下文调用lexRuntimeClient.postText(textRequest)取得机器人的message回复若lanCode不是en调用textTranslateFromEn将英文回复回译成用户语言后返回否则直接返回。注意构造PostTextRequest时botAlias必须替换为你在第 2 步发布机器人时填写的实际别名否则调用会因找不到别名而失败。DetectLanguage用 Comprehend 识别语言该私有方法构建ComprehendClient将用户输入包装成DetectDominantLanguageRequest后调用detectDominantLanguage从返回的languages()列表按置信度排序中取出语言代码。例如法语输入返回fr、意大利语输入返回it。双向翻译textTranslateToEn / textTranslateFromEn这两个公有方法都使用TranslateClient并且显式设置了EnvironmentVariableCredentialsProvider作为凭证来源即从环境变量AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY以及可选的AWS_SESSION_TOKEN读取凭证。差异只在于翻译方向textTranslateToEnsourceLanguageCode为检测出的lanCodetargetLanguageCode固定为entextTranslateFromEnsourceLanguageCode固定为entargetLanguageCode为lanCode。TranslateTextRequest textRequest TranslateTextRequest.builder() .sourceLanguageCode(lanCode) // 例如 fr .targetLanguageCode(en) // 目标语言 .text(text) .build();从仓库源码可以推断LexService用Component注解注册为 Spring Bean因此BotController中的Autowired LexService lex才能完成依赖注入——这也是 Web 层与 AWS 服务层解耦的关键设计。创建 HTML 前端页面完成 Java 文件后在src/main/resources下创建templates文件夹并在其中创建index.html作为应用首页展示聊天机器人。完整代码如下!DOCTYPE html html xmlns:thhttps://www.thymeleaf.org head titleAmazon Lex - Sample Application (BookTrip)/title script th:src|https://code.jquery.com/jquery-1.12.4.min.js|/script style languagetext/css input#wisdom { padding: 4px; font-size: 1em; width: 400px } input::placeholder { color: #ccc; font-style: italic; } p.userRequest { margin: 4px; padding: 4px 10px 4px 10px; border-radius: 4px; min-width: 50%; max-width: 85%; float: left; background-color: #7d7; } p.lexResponse { margin: 4px; padding: 4px 10px 4px 10px; border-radius: 4px; text-align: right; min-width: 50%; max-width: 85%; float: right; background-color: #bbf; font-style: italic; } p.lexError { margin: 4px; padding: 4px 10px 4px 10px; border-radius: 4px; text-align: right; min-width: 50%; max-width: 85%; float: right; background-color: #f77; } /style /head body h1 styletext-align: leftAmazon Lex - BookTrip/h1 p stylewidth: 400px This multiple language chatbot shows you how easy it is to incorporate a hrefhttps://aws.amazon.com/lex/ titleAmazon Lex (product) target_newAmazon Lex/a into your web apps. Try it out. /p div idconversation stylewidth: 400px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll/div input typetext idwisdom size80 valueI need a hotel room br button onclickpushChat()Send Text/button script typetext/javascript var g_text ; // set the focus to the input box document.getElementById(wisdom).focus(); function pushChat() { // if there is text to be sent... var wisdomText document.getElementById(wisdom); if (wisdomText wisdomText.value wisdomText.value.trim().length 0) { // disable input to show were sending it var wisdom wisdomText.value.trim(); wisdomText.value ...; wisdomText.locked true; handletext(wisdom); } } function showRequest() { var conversationDiv document.getElementById(conversation); var requestPara document.createElement(P); requestPara.className userRequest; requestPara.appendChild(document.createTextNode(g_text)); conversationDiv.appendChild(requestPara); conversationDiv.scrollTop conversationDiv.scrollHeight; } function showResponse(lexResponse) { var conversationDiv document.getElementById(conversation); var responsePara document.createElement(P); responsePara.className lexResponse; var lexTextResponse lexResponse; responsePara.appendChild(document.createTextNode(lexTextResponse)); responsePara.appendChild(document.createElement(br)); conversationDiv.appendChild(responsePara); conversationDiv.scrollTop conversationDiv.scrollHeight; } function handletext(text) { g_text text $.ajax(/text, { type: POST, data: text text, success: function (data, status, xhr) { showRequest(); showResponse(data); // re-enable input var wisdomText document.getElementById(wisdom); wisdomText.value ; wisdomText.locked false; }, error: function (jqXhr, textStatus, errorMessage) { $(p).append(Error errorMessage); } }); } /script /body /html前端页面的关键机制对话区#conversation是一个带滚动条的div用户消息userRequest绿色左对齐与机器人回复lexResponse蓝色右对齐以动态创建的p节点追加其中发送逻辑pushChat()读取输入框#wisdom的内容经handletext()通过 jQuery$.ajax以POST方式把text参数提交到/text端点异步刷新success回调先showRequest()显示用户原文再showResponse(data)显示后端返回的机器人回复之后清空输入框恢复可输入状态。整个前端不依赖刷新页面配合后端的“识别 → 翻译 → 对话 → 回译”流水线实现了无缝的多语言聊天体验。下图展示法语输入场景下机器人同样以法语追问城市信息运行应用在 IntelliJ 中打开 Spring Boot 主类BotExample点击运行图标即可启动应用。首次启动会通过内嵌 Tomcat 提供 Web 服务浏览器访问首页后即可与多语言聊天机器人对话。几点运行提醒运行时需保证环境变量中配置了有效的 AWS 凭证AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY因为TranslateClient使用了EnvironmentVariableCredentialsProvider所有 AWS 客户端均固定使用us-east-1区域请在支持 Lex、Comprehend、Translate 的区域环境运行若用 IntelliJ 的 Run Configuration 运行可以在启动前在 IDE 的 Environment variables 中填入上述凭证变量。部署提示你也可以把该 Spring Boot 应用部署到 AWS Elastic Beanstalk。若选择 Elastic Beanstalk 部署需要在环境中额外配置一条**入站规则inbound rule**以允许外部访问应用端口。关于创建和部署 AWS Java Web 应用的完整流程可参考仓库中的姊妹教程 javav2/usecases/creating_first_project/README.md。后续建议Next steps至此你已经完成了一个使用 Amazon Lex 打造交互式体验的 Spring Boot 应用并且具备真正的多语言能力。请务必记得教程中创建的所有 AWS 资源Lex 机器人、相关服务都需要在结束后清理终止以避免持续产生费用。如需更多 AWS 多服务组合示例可以继续浏览仓库的 javav2/usecases 目录其中包含照片分析应用、SNS 消息应用、Redshift 数据追踪等多种端到端用例帮助你进一步掌握 AWS SDK for Java v2 的综合实战能力。赞分享示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载相关推荐使用 AWS SDK for JavaScript v3 在 Web 应用中构建多语言 Amazon Lex 聊天机器人lex-bot 示例使用 AWS SDK for JavaScript v3 在 Web 应用中构建多语言 Amazon Lex 聊天机器人lex bot 示例 导读 本文围绕示例工程教程后端AWS SDK for Java v2聊天机器人Lex对话机器人开发AWS SDK for Java v2聊天机器人Lex对话机器人开发 概述 Amazon Lex是AWS提供的对话机器人服务它使用与Alexa相同的深度学习后端Spring Boot 与 AWS SDK for Java v2构建 Amazon Aurora Serverless 工作项追踪 REST 应用Spring Boot 与 AWS SDK for Java v2构建 Amazon Aurora Serverless 工作项追踪 REST 应用 本篇以示例工程教程后端创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
02
RELATED NEWS

相关资讯

更多网站建设与数字化升级内容

03
WHY YAOTU

想打造同款高转化官网?

懂行业、懂生意,从建站到增长一站式陪跑

◈

场景化定制

不做模板站,围绕你的业务场景量身设计,小众不撞款。

◐

营销型架构

以转化目标组织内容与路径,让官网真正带来询盘。

▲

全周期服务

设计、开发、运营、运维一体,上线只是开始。

免费获取你的建站方案

留下需求,专属顾问 24 小时内为你输出方案建议。