Java 程序员第 40 阶段05:从零搭建 Java 大模型完整项目,接口层设计与API开发

发布时间:2026/5/30 11:34:34

Java 程序员第 40 阶段05:从零搭建 Java 大模型完整项目,接口层设计与API开发 概述本文介绍Java大模型项目的接口层设计与API开发涵盖RESTful API设计规范、对话接口实现同步流式SSE、知识库问答接口、文件上传与处理接口以及API文档Swagger集成。1 RESTful API设计规范1.1 API设计原则- **资源导向**以名词而非动词命名 endpoint- **HTTP方法对应**GET查询、POST创建、PUT更新、DELETE删除- **版本控制**通过URL路径 /api/v1/ 进行版本管理- **统一响应格式**所有接口返回统一JSON结构1.2 统一响应格式public class ApiResponseT {private int code;private String message;private T data;private long timestamp;public static T ApiResponseT success(T data) {return new ApiResponse(200, success, data, System.currentTimeMillis());}public static T ApiResponseT error(int code, String message) {return new ApiResponse(code, message, null, System.currentTimeMillis());}}1.3 接口路径规范| 模块 | 前缀 | 示例 ||------|------|------|| 对话 | /api/v1/chat | POST /api/v1/chat/stream || 知识库 | /api/v1/knowledge | POST /api/v1/knowledge/query || 文件 | /api/v1/file | POST /api/v1/file/upload || 用户 | /api/v1/user | GET /api/v1/user/profile |2 对话接口实现2.1 同步对话接口RestControllerRequestMapping(/api/v1/chat)RequiredArgsConstructorpublic class ChatController {private final ChatService chatService;PostMapping(/sync)public ApiResponseChatResponse syncChat(RequestBody ChatRequest request) {return ApiResponse.success(chatService.chat(request));}}2.2 流式对话接口SSESSEServer-Sent Events实现流式输出GetMapping(value /stream, produces MediaType.TEXT_EVENT_STREAM_VALUE)public FluxString streamChat(RequestParam String message) {return chatService.streamChat(message).map(chunk - data: chunk \n\n).concatWith(Flux.just(data: [DONE]\n\n));}2.3 前端调用示例const eventSource new EventSource(/api/v1/chat/stream?message${encodeURIComponent(input)});eventSource.onmessage (event) {if (event.data [DONE]) {eventSource.close();} else {appendToChat(event.data);}};3 知识库问答接口3.1 接口设计PostMapping(/query)public ApiResponseKnowledgeResponse query(RequestBody KnowledgeQueryRequest request) {// 1.向量相似度检索ListDocument documents knowledgeService.search(request.getQuery(),request.getTopK());// 2.构建提示词String prompt buildPrompt(documents, request.getQuery());// 3.调用大模型生成答案String answer llmService.chat(prompt);return ApiResponse.success(new KnowledgeResponse(answer, documents));}3.2 检索增强生成RAG用户查询→向量检索→ TopK相关文档→构建提示词→ LLM生成→返回答案4 文件上传与处理接口4.1 文件上传ControllerPostMapping(/upload)public ApiResponseFileUploadResponse upload(RequestParam(file) MultipartFile file,RequestParam(value type, defaultValue document) String type) {// 1.文件校验validateFile(file);// 2.保存文件String fileId fileService.store(file, type);// 3.异步处理文本提取、向量化asyncProcess(fileId);return ApiResponse.success(new FileUploadResponse(fileId, file.getOriginalFilename()));}4.2 支持的文件类型| 类型 | 扩展名 | 处理方式 ||------|--------|----------|| 文本 | txt, md, json | 直接解析 || Word | docx, doc | Apache POI || PDF | pdf | PDFBox解析 || 表格 | xlsx, csv | EasyExcel |5 API文档Swagger集成5.1 SpringDoc配置springdoc:api-docs:path: /api-docsswagger-ui:path: /swagger-ui.htmlenabled: true5.2 接口注解示例Operation(summary 流式对话接口,description 支持SSE流式输出的对话接口适用于需要实时响应的场景)ApiResponse(responseCode 200,description 成功,content Content(mediaType text/event-stream))GetMapping(value /stream, produces MediaType.TEXT_EVENT_STREAM_VALUE)public FluxString streamChat(RequestParam String message) {// ...}5.3 访问地址- Swagger UI: http://localhost:8080/swagger-ui.html- API Docs: http://localhost:8080/api-docs6 接口安全设计6.1 认证机制采用JWT Token认证Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(auth - auth.requestMatchers(/api/v1/auth/**).permitAll().requestMatchers(/swagger-ui/**, /api-docs/**).permitAll().anyRequest().authenticated()).addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);return http.build();}6.2 限流策略使用Redis实现接口限流AspectComponentpublic class RateLimitAspect {Autowiredprivate RedisTemplateString, String redisTemplate;Around(annotation(rateLimit))public Object rateLimit(ProceedingJoinPoint point, RateLimit rateLimit) throws Throwable {String key getKey(point);Long count redisTemplate.opsForValue().increment(key);if (count ! null count rateLimit.maxRequests()) {throw new BizException(请求过于频繁请稍后重试);}return point.proceed();}}7 总结本文介绍了Java大模型项目的接口层设计与实现涵盖了- RESTful API设计规范和统一响应格式- 同步与流式SSE对话接口实现- 知识库问答接口的RAG架构- 文件上传与处理接口- Swagger API文档集成- 接口安全认证与限流策略这些接口设计为上层应用提供了完整的与大模型交互的能力。

相关新闻