环境准备JDK 17+Spring Boot 3.xMaven 3.8+

发布时间:2026/6/30 2:37:30

环境准备JDK 17+Spring Boot 3.xMaven 3.8+ 添加依赖dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-webflux/artifactId /dependency dependency groupIdcom.fasterxml.jackson.core/groupId artifactIdjackson-databind/artifactId /dependency回到顶部三、配置 application.ymldeepseek: api-key: sk-xxxxxxxxxxxxxxxx base-url: https://api.deepseek.com model: deepseek-chat max-tokens: 2048回到顶部四、创建配置类Configuration ConfigurationProperties(prefix deepseek) Data public class DeepSeekConfig { private String apiKey; private String baseUrl; private String model; private Integer maxTokens; Bean public WebClient deepSeekWebClient() { return WebClient.builder() .baseUrl(baseUrl) .defaultHeader(Authorization, Bearer apiKey) .defaultHeader(Content-Type, application/json) .build(); } }回到顶部五、定义请求/响应实体// 请求体 Data public class ChatRequest { private String model; private ListMessage messages; JsonProperty(max_tokens) private Integer maxTokens; private Boolean stream false; Data AllArgsConstructor public static class Message { private String role; // system / user / assistant private String content; } } // 响应体 Data public class ChatResponse { private String id; private ListChoice choices; Data public static class Choice { private Message message; } Data public static class Message { private String role; private String content; } }回到顶部六、实现Service层Service RequiredArgsConstructor public class DeepSeekService { private final WebClient deepSeekWebClient; private final DeepSeekConfig config; public String chat(String userMessage) { ChatRequest request new ChatRequest(); request.setModel(config.getModel()); request.setMaxTokens(config.getMaxTokens()); request.setMessages(List.of( new ChatRequest.Message(system, 你是一个专业Java开发助手), new ChatRequest.Message(user, userMessage) )); ChatResponse response deepSeekWebClient .post() .uri(/v1/chat/completions) .bodyValue(request) .retrieve() .bodyToMono(ChatResponse.class) .block(); return response.getChoices().get(0).getMessage().getContent(); } }回到顶部七、实现Controller层RestController RequestMapping(/api/ai) RequiredArgsConstructor public class AiController { private final DeepSeekService deepSeekService; PostMapping(/chat) public ResponseEntityString chat(RequestBody MapString, String body) { String message body.get(message); String reply deepSeekService.chat(message); return ResponseEntity.ok(reply); } }回到顶部八、测试curl -X POST http://localhost:8080/api/ai/chat \ -H Content-Type: application/json \ -d {message: 帮我写一个Spring Boot分页查询的示例}

相关新闻