当前位置: 代码网 > it编程>编程语言>Java > SpringAI+Ollama本地大模型的配置指南

SpringAI+Ollama本地大模型的配置指南

2026年08月19日 Java 我要评论
一、引言ollama 是轻量化本地大模型部署工具,支持一键部署 qwen、llama、llava 等各类开源模型,无需复杂算力与编译配置,可实现本地私有化、零网络开销、数据不外泄的大模型推理能力。sp

一、引言

ollama 是轻量化本地大模型部署工具,支持一键部署 qwen、llama、llava 等各类开源模型,无需复杂算力与编译配置,可实现本地私有化、零网络开销、数据不外泄的大模型推理能力。springai 是 spring 官方标准化 ai 开发框架,提供统一的模型调用抽象 api,可无缝适配云端模型与本地 ollama 模型,实现业务代码无感切换。

本文基于 springboottest 单元测试 实现全套实战能力,无需启动 web 容器,专注模型调用调试,覆盖同步对话、流式输出、多模态图文识别三大核心场景,所有代码可直接运行、注释完整、适合学习与项目落地。

二、环境搭建与工程配置

2.1 ollama 安装与模型拉取

本地部署 ollama 并拉取对应模型,分别适配文本对话与图文多模态场景,终端执行以下命令:

  1. 安装 ollama 客户端,默认本地服务地址:http://localhost:11434
  2. 拉取通用文本对话模型:ollama pull qwen3:7b
  3. 拉取多模态图文识别模型:ollama pull llava:7b

2.2 项目核心依赖(maven)

项目基于 springboot3,需引入 springai ollama 核心依赖、webflux 流式依赖、单元测试依赖,完整依赖如下:

<?xml version="1.0" encoding="utf-8"?>
<dependencies>
    <!-- springai ollama 核心适配依赖 -->
    <dependency>
        <groupid>org.springframework.ai</groupid>
        <artifactid>spring-ai-starter-model-ollama</artifactid>
        <version>1.0.0-m1</version>
    </dependency>
    <!-- 流式输出必备 webflux 响应式依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-webflux</artifactid>
    </dependency>
    <!-- springboot 单元测试依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

2.3 全局配置文件(application.yml)

统一配置 ollama 本地地址、默认模型、推理参数,所有测试类自动读取生效:

spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        options:
          model: qwen3:7b
          temperature: 0.3
          num-ctx: 4096

三、测试工程通用规范

本文所有测试用例统一遵循以下规范,保证代码一致性与可复用性:

  1. 使用 @springboottest 注解加载 spring 上下文,自动注入 ollama 模型客户端;
  2. 同步调用适用于离线批量处理,流式调用适用于实时分段输出场景;
  3. 多模态场景手动切换 llava:7b 模型,覆盖图文识别能力;
  4. 所有用例无需启动 tomcat 容器,直接运行单元测试即可调试模型效果。

四、实战一:同步 chat 对话单元测试

4.1 场景说明

同步调用为一次性阻塞请求,模型完整生成全部内容后统一返回结果,适合离线文本总结、批量问答、后台业务处理场景,代码简单、调试稳定。

4.2 完整可运行代码

import jakarta.annotation.resource;
import org.junit.jupiter.api.test;
import org.springframework.ai.chat.prompt.prompt;
import org.springframework.ai.ollama.ollamachatmodel;
import org.springframework.ai.ollama.api.ollamachatoptions;
import org.springframework.boot.test.context.springboottest;
/**
 * ollama 同步对话单元测试
 * 适用场景:离线问答、文本总结、批量数据处理
 */
@springboottest
public class ollamasyncchattest {
    // 自动注入ollama模型客户端,读取yml全局配置
    @resource
    private chatmodel ollamachatmodel;
    @test
    void testsyncchat() {
        // 1. 定义用户提问内容
        string question = "用简短语言解释springai是什么";
        //手动设置大模型
        ollamachatoptions ollamachatoptions = ollamachatoptions.builder()
                .model("qwen2.5:7b")
                .build();
        // prompt第二个参数:传入本次运行时option
        prompt prompt = new prompt(question, ollamachatoptions);
        // 3. 同步调用本地大模型,阻塞等待完整返回
        var chatresponse = ollamachatmodel.call(prompt);
        // 4. 标准化提取ai回答内容
        string answer = chatresponse.getresult().getoutput().gettext();
        // 控制台输出结果,方便调试查看
        system.out.println("===== 同步问答完整回答 =====");
        system.out.println(answer);
    }
}

五、实战二:sse 流式输出单元测试

5.1 场景说明

流式输出基于 webflux 响应式 flux 实现,模型逐段返回文本分片,模拟前端打字机效果,解决长文本超时、响应卡顿问题,适配实时对话、交互式问答场景。单元测试通过 blocklast() 阻塞主线程,等待全部数据流接收完毕。

5.2 完整可运行代码

import org.junit.jupiter.api.test;
import org.springframework.ai.chat.model.chatmodel;
import org.springframework.ai.chat.prompt.prompt;
import org.springframework.ai.chat.prompt.prompttemplate;
import org.springframework.boot.test.context.springboottest;
import reactor.core.publisher.flux;
import javax.annotation.resource;
import java.util.map;
import java.util.stringjoiner;
/**
 * ollama 流式对话单元测试
 * 适用场景:实时对话、打字机效果、长文本流式输出
 */
@springboottest
public class ollamastreamchattest {
    @resource
    private chatmodel ollamachatmodel;
    @test
    void teststreamchat() {
        // 1. 定义用户提问内容
        string question = "用简短语言解释springai是什么";
        //手动设置大模型
        ollamachatoptions ollamachatoptions = ollamachatoptions.builder()
                .model("qwen2.5:7b")
                .build();
        // prompt第二个参数:传入本次运行时option
        prompt prompt = new prompt(question, ollamachatoptions);
        // 用于拼接所有流式分片,生成完整回答
        stringjoiner fullcontent = new stringjoiner("");
        // 开启流式响应,逐段接收模型输出
        flux<string> streamflux = ollamachatmodel.stream(prompt)
                .map(resp -> resp.getresult().getoutput().gettext())
                .doonnext(chunk -> {
                    // 实时打印每一段分片,模拟前端实时渲染
                    system.out.print(chunk);
                    fullcontent.add(chunk);
                });
        // 阻塞主线程,等待所有流式数据推送完成
        streamflux.blocklast();
        // 输出拼接后的完整回答
        system.out.println("\n\n===== 流式拼接完整内容 =====");
        system.out.println(fullcontent);
    }
}

六、实战三:多模态图文识别单元测试

6.1 场景说明

基于 llava:7b 多模态模型,支持图片+文本联合提问,实现图片内容识别、图像描述、看图问答等能力,可应用于图片解析、截图分析、图像内容审核等场景。

6.2 完整可运行代码

import org.junit.jupiter.api.test;
import org.springframework.ai.chat.messages.usermessage;
import org.springframework.ai.chat.model.chatmodel;
import org.springframework.ai.chat.prompt.prompt;
import org.springframework.ai.chat.prompt.chatoptions;
import org.springframework.boot.test.context.springboottest;
import org.springframework.core.io.urlresource;
import javax.annotation.resource;
import java.net.malformedurlexception;
/**
 * ollama 多模态图文识别单元测试
 * 依赖模型:llava:7b
 * 功能:图片解析、图文问答、图像内容描述
 */
@springboottest
public class ollamamultimodaltest {
    @resource
    private chatmodel ollamachatmodel;
    @test
    void testimagechat() throws malformedurlexception {
        // 1. 动态覆盖模型,指定多模态图文模型
        chatoptions multimodeloptions = chatoptions.builder()
                .model("llava:7b")
                .temperature(0.2)
                .build();
        // 2. 替换为自己的有效可访问图片公网链接
        // 1。本地磁盘绝对路径 d:/test/a.jpg 或者 /opt/image/a.jpg
        string localfilepath = "c:/users/65739/downloads/ac1db2e4-80fb-4f92-bdc2-95a28b16dd75-1.png";
        filesystemresource imageresource = new filesystemresource(localfilepath);
        //2.资源文件下的图片路径
//        classpathresource imageresource = new classpathresource("image/cat.jpg");
        // 3. 替换为自己的有效可访问图片公网链接
//        string imageurl = "https://pic.baike.soso.com/ugc/baikepic2/21123/20220313152217_9856.jpg/0";
//        urlresource imageresource = new urlresource(imageurl);
        //2.构建media对象,封装图片资源 + mime类型
        media media = media.builder()
                .mimetype(mimetypeutils.image_jpeg)
                .data(imageresource)
                .build();
        //3.构建usermessage,文本+图片媒体
        string userquestion = "详细描述这张图片里面有什么内容";
        usermessage usermsg = usermessage.builder()
                .text(userquestion)
                .media(media)
                .build();
        //4.组装prompt,同时运行时指定多模态模型(llava)
        prompt prompt = new prompt(list.of(usermsg), multimodeloptions);
        var response = ollamachatmodel.call(prompt);
        string result = response.getresult().getoutput().gettext();
        // 输出图片识别结果
        system.out.println("===== 图片识别回答 =====");
        system.out.println(result);
    }
}

七、运行注意事项与避坑指南

  1. 服务前置校验:运行测试前必须启动 ollama 本地服务,确保 127.0.0.1:11434 可正常访问。
  2. 模型匹配校验:图文多模态场景必须指定 llava:7b,文本模型无法解析图片资源。
  3. 流式依赖必填:流式输出必须引入 webflux 依赖,否则 flux 响应式类无法加载,测试报错。
  4. 硬件适配说明:7b 模型建议 4g 及以上独立显卡,无 n 卡将走 cpu 推理,速度大幅降低。
  5. 图片资源规范:多模态测试需使用有效可访问图片链接,无效/失效图片地址会导致解析失败。

八、方案优势总结

  1. 调试高效:基于单元测试运行,无需启动 web 容器,节省项目启动耗时。
  2. 数据安全:全程本地模型推理,业务数据不上公网,满足私有化合规需求。
  3. 代码通用:遵循 springai 统一 api,可无缝迁移为 web 接口或云端模型调用。
  4. 场景全覆盖:同时支持文本问答、流式交互、图文多模态,满足绝大多数本地 ai 开发场景。

以上就是springai+ollama本地大模型的配置指南的详细内容,更多关于springai ollama本地大模型的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com