项目初始化与 DeepSeek 配置
约 464 字大约 2 分钟
布欧-Lewyon
2026-06-08
首页 › Agent Spring Boot › WebFlux 与流式 API
工程结构(agent-web-flux)
agent-web-flux/
├── pom.xml
├── src/main/java/com/lewyon/webflux/
│ ├── WebFluxApplication.java
│ ├── controller/ChatController.java
│ └── service/ChatService.java
├── src/main/resources/
│ ├── application.yml
│ └── static/ # frontend 构建产物
└── frontend/ # React + Vite + Ant Design只有 4 个 Java 源文件,刻意保持最小,方便对照学习。
pom.xml 依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.6</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>无 spring-boot-starter-web、无 Spring AI、无 Redis。Java 17。
application.yml
spring:
application:
name: web-flux
server:
port: 8080
deepseek:
model: deepseek-v4-flash
api:
url: https://api.deepseek.com
key: ${DEEPSEEK_API_KEY} # 建议环境变量,勿提交仓库WebClient 初始化(ChatService)
ChatService 构造函数里组装 WebClient:
this.webClient = WebClient.builder()
.baseUrl(apiUrl)
.defaultHeader("Authorization", "Bearer " + apiKey)
.defaultHeader("Content-Type", "application/json")
.build();请求体符合 OpenAI Chat Completions 格式:
Map<String, Object> requestBody = Map.of(
"model", model,
"messages", List.of(Map.of("role", "user", "content", question)),
"stream", true
);探活接口
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*") // 开发期;生产收紧域名
public class ChatController {
private final ChatService chatService;
@GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamChat(@RequestParam String message) {
return chatService.streamChat(message);
}
}前端构建进 Spring Boot
frontend/vite.config.ts:
export default defineConfig({
build: {
outDir: '../src/main/resources/static',
emptyOutDir: true,
},
server: {
proxy: {
'/api': 'http://localhost:8080',
},
},
});开发:cd frontend && npm run dev(5173 代理到 8080)
发布:npm run build 后 mvn spring-boot:run,访问 http://localhost:8080
验证
export DEEPSEEK_API_KEY=sk-xxx
./mvnw spring-boot:run
curl -N "http://localhost:8080/api/chat/stream?message=你好"应看到逐段 SSE 输出,末尾有 [DONE]。
学习点
| 知识点 | 说明 |
|---|---|
| Boot 4 + Jackson 3 | ObjectMapper 包名为 tools.jackson.databind |
| 仅 WebFlux | 避免 web + webflux 混用两套 Controller 风格 |
| API Key | 用环境变量,生产走配置中心 |
| static 集成 | 前后端同 jar,部署简单 |
小结
agent-web-flux依赖极少:WebFlux + WebClient + DeepSeek 配置。ChatController暴露/api/chat/stream,ChatService负责上游流式调用。- 前端 Vite 产物打进
static/,开发用 proxy。
上一节:专栏导读
下一节:WebClient 流式解析与 SSE
