springboot怎么调用本地部署的deepseek
时间: 2025-03-02 19:11:11 浏览: 103
### 如何从 Spring Boot 应用程序调用本地部署的 DeepSeek API
为了实现这一目标,在 `application.properties` 或者 `application.yml` 文件中配置 DeepSeek 的 API 密钥以及其他必要的连接参数[^1]:
```properties
deepseek.api.key=你的API密钥
deepseek.api.url=http://localhost:8080/api/deepseek # 假设DeepSeek运行在同一台机器上,默认端口为8080
```
创建用于访问 DeepSeek API 的服务类。此服务负责构建请求并解析来自 DeepSeek API 的响应。
#### 构建 RestTemplate Bean
在 Spring Boot 中,可以利用 `RestTemplate` 发起 HTTP 请求。定义一个名为 `restTemplateConfig` 的配置类来设置 `RestTemplate` 实例:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
```
#### 定义 Service 类
接下来编写具体的服务逻辑,假设想要获取某些分析结果作为例子展示如何发起 GET 请求给 DeepSeek API :
```java
@Service
public class DeepSeekService {
private final String apiKey;
private final String apiUrl;
private final RestTemplate restTemplate;
@Autowired
public DeepSeekService(@Value("${deepseek.api.key}") String apiKey,
@Value("${deepseek.api.url}") String apiUrl,
RestTemplate restTemplate){
this.apiKey = apiKey;
this.apiUrl = apiUrl.endsWith("/") ? apiUrl : apiUrl+"/";
this.restTemplate = restTemplate;
}
/**
* 获取指定ID的数据分析报告.
*/
public AnalysisReport getAnalysisById(String id) throws Exception{
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer "+apiKey);
HttpEntity<String> entity = new HttpEntity<>("parameters",headers);
ResponseEntity<AnalysisReport> response =
restTemplate.exchange(
apiUrl+"analysis/{id}", HttpMethod.GET,entity,AnalysisReport.class,id);
if(response.getStatusCode().is2xxSuccessful()){
return response.getBody();
}else{
throw new RuntimeException("Failed to fetch analysis report");
}
}
}
// 数据传输对象 (DTO), 对应于预期自 DeepSeek 返回的结果结构
class AnalysisReport {
// 根据实际返回值调整字段...
private Long id;
private String title;
private Date createdAt;
// getter/setter 省略...
// 如果需要支持 JSON 反序列化,则可能还需要无参构造函数和 Lombok 注解等辅助工具
}
```
上述代码片段展示了怎样通过注入的方式获得之前配置好的属性值,并使用这些信息向 DeepSeek 提交带有认证头的 GET 请求以检索特定 ID 关联的数据分析报告实例。注意这里假定 DeepSeek 支持 Bearer Token 方式的身份验证机制;如果不是这种情况,请参照官方文档适配相应的授权方式[^2]。
阅读全文
相关推荐

















