Spring AI与Ollama本地大模型集成实践 📅 2026/7/24 3:42:51 1. 项目背景与核心价值去年在开发一个智能客服系统时我遇到了一个典型的技术困境既想使用大语言模型的强大能力又受限于数据隐私和API调用成本。当时尝试了多种方案都不够理想直到发现Spring AI与Ollama的组合。这个技术栈完美解决了我的痛点——既能享受AI能力又能完全掌控数据流向。Spring Boot 3作为当前Java生态中最主流的应用框架其自动配置、依赖管理等特性为AI集成提供了绝佳基础。而Spring AI项目则是Spring官方推出的AI能力抽象层它统一了不同AI供应商的接口规范。Ollama这个工具更是个宝藏它让我们能在本地Mac/Windows/Linux机器上运行Llama2、Mistral等开源大模型。2. 环境准备与依赖配置2.1 基础环境要求我的开发环境是MacBook Pro M1芯片实测以下配置可以流畅运行7B参数的模型JDK 17Spring Boot 3.2.4至少16GB内存运行7B模型需要8GB空闲内存Ollama 0.1.23对于Windows用户建议使用WSL2来运行Ollama能获得更好的性能表现。Linux环境下直接运行即可注意提前安装NVIDIA驱动如果使用GPU加速。2.2 关键依赖引入在pom.xml中添加以下依赖Gradle版本请自行转换dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-ollama-spring-boot-starter/artifactId version0.8.1/version /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency特别注意Spring AI的版本迭代较快建议通过Spring Initializr生成项目时勾选AI模块可以自动匹配兼容版本。3. Ollama本地模型部署3.1 模型下载与运行在终端执行以下命令安装并启动Ollama服务# 安装Ollama curl -fsSL https://ollama.com/install.sh | sh # 下载模型以Llama2 7B为例 ollama pull llama2:7b # 启动服务默认监听11434端口 ollama serve我测试过几个模型的资源消耗情况llama2:7bCPU模式约占用8GB内存mistral:7b量化版仅需4GB内存phi:2.7b适合低配设备内存占用约3GB重要提示首次运行会下载数GB的模型文件请确保网络畅通。模型默认保存在~/.ollama目录3.2 模型API验证启动后可以通过curl测试API是否正常curl http://localhost:11434/api/generate -d { model: llama2:7b, prompt: 为什么天空是蓝色的 }正常会返回流式响应类似{response:这是由瑞利散射现象导致的...}4. Spring Boot集成实战4.1 基础配置在application.yml中添加spring: ai: ollama: base-url: http://localhost:11434 chat: model: llama2:7b temperature: 0.7关键参数说明temperature控制生成随机性0-1top-p核采样阈值默认0.9max-tokens单次响应最大token数4.2 核心服务实现创建ChatService.javaService public class ChatService { private final OllamaChatClient chatClient; public ChatService(OllamaChatClient chatClient) { this.chatClient chatClient; } public String generate(String prompt) { PromptTemplate promptTemplate new PromptTemplate( 你是一个专业的技术顾问。请用中文回答以下问题。 问题{question} 回答); Prompt engineeredPrompt promptTemplate.create( Map.of(question, prompt)); return chatClient.call(engineeredPrompt).getResult().getOutput().getContent(); } }这段代码展示了几个关键技巧使用PromptTemplate进行提示词工程通过构造函数注入OllamaChatClient对原始prompt进行封装增强4.3 REST接口暴露创建ChatController.javaRestController RequestMapping(/api/chat) public class ChatController { private final ChatService chatService; // 构造器注入 public ChatController(ChatService chatService) { this.chatService chatService; } PostMapping public ResponseEntityString chat(RequestBody String prompt) { return ResponseEntity.ok(chatService.generate(prompt)); } }5. 高级功能实现5.1 流式响应处理修改Controller支持SSEGetMapping(/stream) public SseEmitter streamChat(RequestParam String prompt) { SseEmitter emitter new SseEmitter(); chatClient.stream(new Prompt(prompt)) .subscribe( chunk - { try { emitter.send(chunk.getResult().getOutput().getContent()); } catch (IOException e) { emitter.completeWithError(e); } }, emitter::completeWithError, emitter::complete ); return emitter; }前端可以通过EventSource连接const eventSource new EventSource(/api/chat/stream?prompt你好); eventSource.onmessage (e) { console.log(e.data); // 实时输出响应片段 };5.2 多模态支持Ollama最新版本已支持图片输入需使用支持多模态的模型如llavaPostMapping(/vision) public String analyzeImage(RequestParam String imageUrl) { var prompt new Prompt(List.of( new UserMessage(描述这张图片内容), new ImageMessage(imageUrl) )); return chatClient.call(prompt).getResult().getOutput().getContent(); }6. 性能优化实践6.1 模型量化技巧通过Ollama运行量化版模型可大幅降低资源占用ollama pull mistral:7b-instruct-q4_K_M量化版本对比q4_04bit量化质量损失明显q5_K_M5bit量化推荐平衡点q8_08bit量化接近原版质量6.2 缓存策略实现添加Spring Cache减少重复计算Cacheable(value aiResponses, key #prompt) public String getCachedResponse(String prompt) { return chatClient.call(new Prompt(prompt)) .getResult().getOutput().getContent(); }配置Caffeine缓存spring: cache: type: caffeine caffeine: spec: maximumSize500,expireAfterWrite10m7. 生产环境注意事项内存管理JVM最大堆内存建议设置为物理内存的50%使用-XX:UseZGC减少GC停顿监控Ollama进程内存使用常驻约800MB超时配置spring: ai: ollama: client: connect-timeout: 30s read-timeout: 5m健康检查Component public class OllamaHealthIndicator implements HealthIndicator { Override public Health health() { try { // 测试API连通性 return Health.up().build(); } catch (Exception e) { return Health.down(e).build(); } } }8. 常见问题排查问题1Ollama服务启动失败检查~/.ollama/logs/server.log确保没有其他进程占用11434端口问题2响应速度慢尝试更小的模型如phi-2添加--numa参数优化CPU绑定设置OLLAMA_NUM_PARALLEL2增加并行度问题3中文输出质量差在prompt中明确要求中文回答尝试chinese-alpaca-2等中文优化模型调整temperature到0.3-0.5范围实测在MacBook Pro M1上7B模型的典型响应时间简单问题3-5秒复杂分析10-15秒长文本生成20秒这套技术栈特别适合需要AI能力但又有数据隐私要求的场景比如企业内部知识库、医疗咨询系统等。我在实际项目中用它处理过客户服务工单分类、合同条款分析等任务相比云端API方案响应速度虽然稍慢但数据安全性有质的提升。