简介:本文详细介绍Spring Boot项目如何集成DeepSeek API,涵盖环境准备、依赖配置、API调用实现及异常处理等全流程,提供可复用的代码示例和最佳实践。
DeepSeek作为新一代AI计算平台,其API为开发者提供了强大的自然语言处理能力。在Spring Boot生态中集成DeepSeek API,可快速构建智能问答、内容生成等AI驱动型应用。本教程通过分步骤讲解,帮助开发者突破技术壁垒,实现从环境搭建到业务落地的完整闭环。
Spring Boot的自动配置特性与DeepSeek API的RESTful风格高度契合,采用HTTP客户端(如RestTemplate或WebClient)可实现高效通信。相较于传统Python调用方案,Java生态的集成具有更好的企业级应用适配性。
在pom.xml中添加核心依赖:
<dependencies><!-- Spring Web模块 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- JSON处理库 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency><!-- 可选:添加日志框架 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies>
https://api.deepseek.com/v1)创建DeepSeekConfig类管理API参数:
@Configuration@ConfigurationProperties(prefix = "deepseek")@Datapublic class DeepSeekConfig {private String apiKey;private String baseUrl = "https://api.deepseek.com/v1";private Integer timeout = 5000; // 毫秒}
在application.yml中配置:
deepseek:api-key: your_actual_api_key_herebase-url: https://api.deepseek.com/v1
@Servicepublic class DeepSeekRestService {@Autowiredprivate DeepSeekConfig config;private final RestTemplate restTemplate;public DeepSeekRestService(RestTemplateBuilder builder) {this.restTemplate = builder.setConnectTimeout(Duration.ofMillis(config.getTimeout())).setReadTimeout(Duration.ofMillis(config.getTimeout())).build();}public String callApi(String endpoint, Object requestBody) {HttpHeaders headers = new HttpHeaders();headers.set("Authorization", "Bearer " + config.getApiKey());headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);ResponseEntity<String> response = restTemplate.postForEntity(config.getBaseUrl() + endpoint,entity,String.class);if (response.getStatusCode().is2xxSuccessful()) {return response.getBody();} else {throw new RuntimeException("API调用失败: " + response.getStatusCode());}}}
@Servicepublic class DeepSeekWebClientService {private final WebClient webClient;public DeepSeekWebClientService(DeepSeekConfig config) {this.webClient = WebClient.builder().baseUrl(config.getBaseUrl()).defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + config.getApiKey()).defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).clientConnector(new ReactorClientHttpConnector(HttpClient.create().responseTimeout(Duration.ofMillis(config.getTimeout())))).build();}public Mono<String> callApi(String endpoint, Object requestBody) {return webClient.post().uri(endpoint).bodyValue(requestBody).retrieve().onStatus(HttpStatus::isError, response -> {return Mono.error(new RuntimeException("API错误: " + response.statusCode()));}).bodyToMono(String.class);}}
创建统一的请求DTO:
@Datapublic class DeepSeekRequest {private String model; // 如:"deepseek-chat"private String prompt;private Integer maxTokens = 2000;private Float temperature = 0.7f;private Integer topP = 1;// 其他可选参数...}
@RestController@RequestMapping("/api/deepseek")public class DeepSeekController {@Autowiredprivate DeepSeekRestService deepSeekService;@PostMapping("/chat")public ResponseEntity<String> chatCompletion(@RequestBody ChatRequest request) {DeepSeekRequest dsRequest = new DeepSeekRequest();dsRequest.setModel("deepseek-chat");dsRequest.setPrompt(request.getMessage());dsRequest.setMaxTokens(request.getMaxTokens() != null ?request.getMaxTokens() : 1000);try {String response = deepSeekService.callApi("/chat/completions", dsRequest);return ResponseEntity.ok(response);} catch (Exception e) {return ResponseEntity.status(500).body("调用失败: " + e.getMessage());}}}
@Asyncpublic CompletableFuture<String> asyncCall(DeepSeekRequest request) {try {String result = deepSeekService.callApi("/chat/completions", request);return CompletableFuture.completedFuture(result);} catch (Exception e) {return CompletableFuture.failedFuture(e);}}
创建响应DTO:
@Datapublic class DeepSeekResponse {private String id;private String object;private Integer created;private String model;private List<Choice> choices;@Datapublic static class Choice {private String text;private Integer index;// 其他字段...}}
@ControllerAdvicepublic class DeepSeekExceptionHandler {@ExceptionHandler(HttpClientErrorException.class)public ResponseEntity<ErrorResponse> handleHttpError(HttpClientErrorException ex) {ErrorResponse error = new ErrorResponse(ex.getStatusCode().value(),ex.getResponseBodyAsString());return new ResponseEntity<>(error, ex.getStatusCode());}@Data@AllArgsConstructorprivate static class ErrorResponse {private int status;private String message;}}
连接池配置:使用Apache HttpClient连接池
@Beanpublic HttpClient httpClient() {PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(200);cm.setDefaultMaxPerRoute(20);return HttpClients.custom().setConnectionManager(cm).build();}
缓存策略:对高频请求实现本地缓存
@Cacheable(value = "deepseekResponses", key = "#prompt")public String getCachedResponse(String prompt) {// 实际API调用}
重试机制:使用Spring Retry实现自动重试
@Retryable(value = {IOException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000))public String retryableCall(DeepSeekRequest request) {// 调用逻辑}
健康检查:添加API可用性监控端点
@RestControllerpublic class HealthController {@Autowiredprivate DeepSeekRestService deepSeekService;@GetMapping("/health/deepseek")public ResponseEntity<String> checkHealth() {try {deepSeekService.callApi("/models", null);return ResponseEntity.ok("OK");} catch (Exception e) {return ResponseEntity.status(503).body("Unavailable");}}}
指标收集:使用Micrometer记录API调用指标
@Beanpublic MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {return registry -> registry.config().commonTags("api", "deepseek");}
日志追踪:添加MDC实现请求链路追踪
public class DeepSeekLoggingInterceptor implements ClientHttpRequestInterceptor {@Overridepublic ClientHttpResponse intercept(HttpRequest request, byte[] body,ClientHttpRequestExecution execution) throws IOException {MDC.put("requestId", UUID.randomUUID().toString());try {return execution.execute(request, body);} finally {MDC.clear();}}}
Authorization: Bearer {apiKey}通过本教程的系统讲解,开发者可以快速掌握Spring Boot与DeepSeek API的集成方法。实际开发中,建议先在测试环境验证API调用逻辑,再逐步迁移到生产环境。对于高并发场景,需特别注意连接池配置和限流策略的实施。