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 示例倉庫。