Spring Boot 中集成 Ollama API 的完整指南,涵盖基础配置、API 调用、性能优化及常见问题解决。
一、环境准备
1. 依赖配置
在 pom.xml
中添加必要的依赖:
<!-- Spring Web (用于 REST 请求) -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><!-- Jackson (JSON 序列化/反序列化) -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency><!-- 可选:WebClient (异步非阻塞请求) -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
2. 配置 Ollama 服务地址
在 application.properties
中配置 Ollama 服务地址:
# Ollama 默认端口为 11434
ollama.api.url=http://localhost:11434/api
二、基础 API 调用
1. 同步请求(使用 RestTemplate)
创建 Service 类调用 Ollama 生成接口:
@Service
public class OllamaService {@Value("${ollama.api.url}")private String ollamaApiUrl;private final RestTemplate restTemplate = new RestTemplate();public String generateText(String model, String prompt) {String url = ollamaApiUrl + "/generate";// 构建请求体Map<String, Object> requestBody = new HashMap<>();requestBody.put("model", model);requestBody.put("prompt", prompt);requestBody.put("stream", false); // 关闭流式响应// 发送 POST 请求ResponseEntity<Map> response = restTemplate.postForEntity(url,requestBody,Map.class);// 解析响应return (String) response.getBody().get("response");}
}
2. 异步请求(使用 WebClient)
配置 WebClient 实现非阻塞调用:
@Configuration
public class WebClientConfig {@Value("${ollama.api.url}")private String ollamaApiUrl;@Beanpublic WebClient ollamaWebClient() {return WebClient.builder().baseUrl(ollamaApiUrl).build();}
}// 调用示例
@Service
public class AsyncOllamaService {@Autowiredprivate WebClient ollamaWebClient;public Mono<String> generateTextAsync(String model, String prompt) {return ollamaWebClient.post().uri("/generate").bodyValue(Map.of("model", model,"prompt", prompt,"stream", false)).retrieve().bodyToMono(Map.class).map(response -> (String) response.get("response"));}
}
三、高级功能集成
1. 流式响应处理
处理 Ollama 的流式输出(逐块返回结果):
public Flux<String> streamText(String model, String prompt) {return ollamaWebClient.post().uri("/generate").bodyValue(Map.of("model", model,"prompt", prompt,"stream", true // 启用流式响应)).retrieve().bodyToFlux(String.class) // 按字符串块接收.map(chunk -> {// 解析 JSON 块(需处理不完整 JSON 情况)try {JsonNode node = new ObjectMapper().readTree(chunk);return node.get("response").asText();} catch (JsonProcessingException e) {return "[解析错误]";}});
}
2. 集成 LangChain
结合 LangChain 的 Spring Boot Starter(需添加依赖):
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-ollama-spring-boot-starter</artifactId><version>0.8.0</version>
</dependency>
配置 application.properties
:
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.model=llama3
直接在代码中调用:
@Autowired
private OllamaChatClient chatClient;public String chat(String message) {return chatClient.call(message);
}
四、性能调优
1. 连接池优化
为同步请求(RestTemplate)配置连接池:
@Bean
public RestTemplate restTemplate() {PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();connectionManager.setMaxTotal(100); // 最大连接数connectionManager.setDefaultMaxPerRoute(20); // 单路由最大连接数CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
}
2. 超时设置
配置请求超时时间(避免阻塞):
// RestTemplate 超时配置
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(5000); // 5秒连接超时
factory.setReadTimeout(30000); // 30秒读取超时
return new RestTemplate(factory);
五、异常处理
1. 自定义异常类
public class OllamaApiException extends RuntimeException {public OllamaApiException(String message) {super("Ollama API 调用失败: " + message);}
}
2. 全局异常拦截
@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(RestClientException.class)public ResponseEntity<String> handleOllamaError(RestClientException e) {return ResponseEntity.status(500).body("Ollama 服务异常: " + e.getMessage());}
}
六、安全增强
1. 添加 API 密钥认证
如果 Ollama 服务启用认证(需手动配置):
// 在请求头中添加密钥
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer your-api-key");HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
restTemplate.postForEntity(url, requestEntity, Map.class);
2. 启用 HTTPS
在 Ollama 服务端配置 HTTPS,Spring Boot 中调用时使用 https://
地址。
七、测试验证
1. 单元测试示例
@SpringBootTest
public class OllamaServiceTest {@Autowiredprivate OllamaService ollamaService;@Testvoid testGenerateText() {String response = ollamaService.generateText("llama3", "你好");assertNotNull(response);System.out.println("Ollama 响应: " + response);}
}
八、总结
-
核心步骤:
- 添加依赖并配置 Ollama 服务地址。
- 使用
RestTemplate
或WebClient
调用 API。 - 处理流式响应和异常。
- 优化连接池和超时设置。
-
推荐实践:
- 生产环境中启用 HTTPS 和 API 密钥认证。
- 使用异步请求(WebClient)提升并发性能。
- 结合 LangChain 简化复杂 AI 任务开发。
完整代码示例可参考 GitHub 示例仓库。