SpringBoot 3.4.2 + DeepSeek 实战:5分钟搞定AI聊天机器人(附完整代码)
·
SpringBoot 3.4.2 + DeepSeek 实战:5分钟搞定AI聊天机器人(附完整代码)
在当今快速发展的AI技术浪潮中,Java开发者如何快速将大模型能力集成到现有系统中?本文将带你从零开始,使用SpringBoot 3.4.2和Spring AI框架,在5分钟内构建一个功能完整的DeepSeek聊天机器人接口。无论你是想为现有系统添加智能对话功能,还是探索AI集成的最佳实践,这篇实战指南都将为你提供清晰的操作路径。
1. 环境准备与项目初始化
在开始之前,确保你的开发环境满足以下要求:
- JDK 17+:SpringBoot 3.x系列需要Java 17或更高版本
- Maven 3.6.3+:推荐使用最新稳定版
- IDE支持:IntelliJ IDEA或VS Code等现代开发工具
使用Spring Initializr快速创建项目骨架:
curl https://start.spring.io/starter.zip \
-d dependencies=web,lombok \
-d javaVersion=17 \
-d artifactId=deepseek-demo \
-d bootVersion=3.4.2 \
-o deepseek-demo.zip
解压后,在pom.xml中添加Spring AI和DeepSeek相关依赖:
<dependencies>
<!-- Spring Boot基础依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring AI OpenAI Starter (兼容DeepSeek) -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.8.1</version>
</dependency>
<!-- 开发辅助工具 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2. 配置DeepSeek API连接
在application.yml中配置DeepSeek服务连接信息:
server:
port: 8080
spring:
ai:
openai:
base-url: https://api.deepseek.com # DeepSeek API端点
api-key: sk-your-api-key-here # 替换为你的实际API密钥
chat:
options:
model: deepseek-chat # 指定使用的模型版本
temperature: 0.7 # 控制生成随机性(0-2)
max-tokens: 1000 # 限制响应长度
提示:DeepSeek API密钥可以通过其官方平台申请,目前提供免费试用额度
3. 核心代码实现
3.1 基础聊天接口
创建ChatController处理用户请求:
@Slf4j
@RestController
@RequestMapping("/api/chat")
public class ChatController {
private final ChatClient chatClient;
// 构造器注入ChatClient.Builder
public ChatController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
@GetMapping("/simple")
public String simpleChat(@RequestParam String message) {
log.info("接收到用户消息: {}", message);
return chatClient.prompt(message).call().content();
}
}
启动应用后,通过curl测试接口:
curl "http://localhost:8080/api/chat/simple?message=Java中的Stream API有什么优势"
3.2 流式响应实现
对于长文本生成场景,流式响应能显著提升用户体验:
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamChat(@RequestParam String message) {
return chatClient.prompt(message)
.stream()
.content();
}
使用HTTPie测试流式接口:
http --stream GET "localhost:8080/api/chat/stream?message=用Java实现快速排序"
3.3 带上下文的对话
实现多轮对话需要维护聊天历史:
@PostMapping("/context")
public String chatWithContext(@RequestBody ChatRequest request) {
// 构建包含系统指令和对话历史的Prompt
Prompt prompt = new Prompt(
List.of(
new SystemMessage("你是一个专业的Java技术专家,回答要简洁专业"),
new UserMessage(request.getMessage())
),
OpenAiChatOptions.builder()
.withModel("deepseek-chat")
.withTemperature(0.5)
.build()
);
return chatClient.prompt(prompt).call().content();
}
// 请求体定义
@Data
static class ChatRequest {
private String message;
}
4. 高级功能扩展
4.1 异常处理
增强接口健壮性的全局异常处理:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleAiServiceException(RuntimeException ex) {
log.error("AI服务调用异常", ex);
return ResponseEntity.status(500)
.body("服务暂时不可用: " + ex.getMessage());
}
}
4.2 性能监控
添加执行耗时监控:
@GetMapping("/timed")
public ChatResponse timedChat(@RequestParam String message) {
long start = System.currentTimeMillis();
String content = chatClient.prompt(message).call().content();
long elapsed = System.currentTimeMillis() - start;
return new ChatResponse(content, elapsed);
}
@Data
@AllArgsConstructor
static class ChatResponse {
private String answer;
private long elapsedMillis;
}
4.3 配置项校验
确保关键配置存在:
@Configuration
@ConfigurationProperties(prefix = "spring.ai.openai")
@Validated
@Data
public class AiConfig {
@NotBlank
private String apiKey;
@NotBlank
private String baseUrl;
@NotNull
private ChatOptions chat;
@Data
public static class ChatOptions {
private String model;
private Double temperature;
private Integer maxTokens;
}
}
5. 部署与优化建议
5.1 生产环境配置
推荐的生产级配置示例:
spring:
ai:
openai:
connect-timeout: 5s
read-timeout: 30s
retry:
max-attempts: 3
initial-interval: 1s
max-interval: 5s
multiplier: 1.5
5.2 安全防护
添加基础安全措施:
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/chat/**").authenticated()
.anyRequest().permitAll()
)
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.ignoringRequestMatchers("/api/chat/**"))
.build();
}
}
5.3 性能优化技巧
- 连接池配置:
spring:
ai:
openai:
rest:
max-connections: 50
max-connections-per-route: 10
- 响应缓存:对常见问题答案添加缓存
@Cacheable(value = "aiResponses", key = "#message")
public String getCachedResponse(String message) {
return chatClient.prompt(message).call().content();
}
- 批量处理:合并多个请求减少API调用次数
6. 完整项目结构参考
deepseek-demo/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ ├── config/
│ │ │ │ ├── AiConfig.java
│ │ │ │ └── SecurityConfig.java
│ │ │ ├── controller/
│ │ │ │ └── ChatController.java
│ │ │ ├── exception/
│ │ │ │ └── GlobalExceptionHandler.java
│ │ │ └── DemoApplication.java
│ │ └── resources/
│ │ ├── application.yml
│ │ └── static/
│ └── test/
└── pom.xml
在实际项目中集成DeepSeek时,建议从简单对话开始,逐步添加复杂功能。Spring AI的模块化设计让扩展变得非常灵活,你可以根据需要组合不同的功能模块。例如,结合Spring Data实现对话历史存储,或集成Spring Security添加细粒度的访问控制。
更多推荐



所有评论(0)