SpringBoot 3.5 + SpringAI 1.0全栈实战:构建智能天气与聊天服务
在当今技术快速迭代的背景下,将AI能力无缝集成到企业应用中已成为开发者的核心诉求。SpringAI作为Spring生态中的AI工程框架,通过模块化设计和统一API抽象,显著降低了AI技术的接入门槛。本文将基于SpringBoot 3.5和SpringAI 1.0,带你从零构建一个融合天气查询与智能聊天功能的完整项目,涵盖阿里云DashScope集成、MyBatis数据层设计等企业级实践。
1. 项目架构与技术选型
1.1 核心模块设计
本项目采用经典的分层架构,各模块职责分明:
spring-ai-demo/
├── ai-service/ # AI核心服务
│ ├── chat/ # 智能聊天模块
│ └── weather/ # 天气服务模块
├── persistence/ # 数据持久层
│ ├── entity/ # 领域对象
│ └── mapper/ # MyBatis接口
├── config/ # 配置中心
│ ├── AiConfig.java # AI模型配置
│ └── DataSourceConfig # 数据源配置
└── web/ # 表现层
├── dto/ # 数据传输对象
└── controller/ # REST控制器
1.2 技术栈组合
| 技术组件 | 版本 | 用途说明 |
|---|---|---|
| Spring Boot | 3.5.0 | 应用基础框架 |
| Spring AI | 1.0.0 | AI能力集成核心 |
| MyBatis | 3.5.13 | 数据持久层框架 |
| MySQL | 8.0+ | 关系型数据库 |
| Lombok | 1.18.30 | 代码简化工具 |
| DashScope | 1.0.0.1 | 阿里云大模型服务 |
| HikariCP | 5.1.0 | 数据库连接池 |
2. 环境准备与基础配置
2.1 依赖管理
在pom.xml中配置核心依赖:
<dependencies>
<!-- SpringAI核心 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
<!-- 阿里云DashScope -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
<version>1.0.0.1</version>
</dependency>
<!-- 数据持久层 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
2.2 应用配置
application.yml关键配置示例:
spring:
datasource:
url: jdbc:mysql://localhost:3306/ai_demo
username: root
password: yourpassword
hikari:
connection-timeout: 30000
maximum-pool-size: 10
ai:
dashscope:
api-key: your-dashscope-key
chat:
model: qwen-max
weather:
api:
key: ${WEATHER_API_KEY}
endpoint: https://api.weatherapi.com/v1
3. AI服务核心实现
3.1 聊天服务构建
ChatClient的配置是SpringAI的核心,支持多模型切换和工具调用:
@Bean
public ChatClient chatClient(
DashScopeChatModel dashScopeModel,
ChatMemory chatMemory,
WeatherTool weatherTool) {
return ChatClient.builder(dashScopeModel)
.defaultSystem("""
您是全栈开发助手,擅长技术问题解答和天气查询。
当前时间:{current_time}
""")
.defaultAdvisors(memoryAdvisor(chatMemory))
.defaultTools(weatherTool)
.build();
}
3.2 工具调用实现
通过@Tool注解实现天气查询工具:
@Service
public class WeatherTool {
@Autowired
private WeatherService weatherService;
@Tool(description = "获取城市天气信息")
public WeatherInfo getWeather(
@ToolParam(description = "城市名称") String city) {
return weatherService.queryByCity(city);
}
}
4. 数据持久层设计
4.1 领域模型定义
使用Lombok简化实体类:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String username;
private String password;
private LocalDateTime createTime;
}
4.2 MyBatis映射配置
动态SQL示例:
<!-- UserMapper.xml -->
<select id="selectByCondition" resultType="User">
SELECT * FROM users
<where>
<if test="username != null">
AND username LIKE CONCAT('%',#{username},'%')
</if>
<if test="status != null">
AND status = #{status}
</if>
</where>
</select>
5. REST API设计
5.1 控制器实现
@RestController
@RequestMapping("/api/chat")
public class ChatController {
@Autowired
private ChatClient chatClient;
@GetMapping("/stream")
public Flux<String> streamChat(
@RequestParam String message) {
return chatClient.prompt()
.user(message)
.stream()
.content();
}
}
5.2 统一异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(AIException.class)
public ResponseEntity<Result<?>> handleAIException(AIException e) {
return ResponseEntity.status(500)
.body(Result.error(e.getMessage()));
}
}
6. 高级特性实现
6.1 对话记忆管理
@Bean
public ChatMemory chatMemory() {
return MessageWindowChatMemory.builder()
.maxMessages(20)
.build();
}
6.2 流式响应优化
前端配合EventSource实现实时显示:
const eventSource = new EventSource('/api/chat/stream?message=你好');
eventSource.onmessage = (e) => {
document.getElementById('output').innerHTML += e.data;
};
7. 生产环境考量
7.1 性能优化建议
- 为ChatClient配置连接池
- 对天气API响应添加缓存
- 启用MyBatis二级缓存
- 限制最大对话历史长度
7.2 安全防护措施
- API密钥通过Vault管理
- 输入参数严格校验
- 对话内容敏感词过滤
- 请求频率限制
在实际项目中,我们发现合理设置对话记忆窗口大小对性能影响显著。当maxMessages超过50时,模型响应延迟会明显增加,建议根据业务场景在15-30条之间调整。
2272



被折叠的 条评论
为什么被折叠?



