SpringAI基于Mysql jdbc方式存储对话记忆

版本

SpringAI:1.1.6

SpringBoot:3.5.14

JdbcChatMemoryRepository

JdbcChatMemoryRepository是一个内置实现,使用 JDBC 将消息存储在关系数据库中。

下面所有配置完成后,应用会在启动时,会读取内置建表语句,schema-mysql.sql,自动创建一张名为 spring_ai_chat_memory 的表,用于存储对话记录

IDEA中双击shift搜索schema-mysql.sql,就能看到建表语句。

使用

引入依赖

xml 复制代码
 <!-- 引入jdbc -->
 <dependency>
     <groupId>org.springframework.ai</groupId>
     <artifactId>spring-ai-starter-model-chat-memory-repository-jdbc</artifactId>
 </dependency>
 <!-- 引入mysql -->
 <dependency>
     <groupId>com.mysql</groupId>
     <artifactId>mysql-connector-j</artifactId>
     <scope>runtime</scope>
 </dependency>

修改配置

使用的是阿里云百炼平台中的大模型,配置如下

spring.ai.chat.memory.repository.jdbc.initialize-schema有三个选项

  • embedded:默认值,只能用于嵌入式数据库(如 H2、HSQL、Derby 等)
  • always:自动使用内置sql创建表
  • never:不初始化,手动创建自定义表
    spring.ai.chat.memory.repository.jdbc.platform的值,是你的数据库类型,当initialize-schema=always时,springai会根据platform使用对应的schema-{platform}.sql文件建表
groovy 复制代码
spring.ai.openai.chat.api-key=
spring.ai.openai.chat.base-url=https://dashscope.aliyuncs.com/compatible-mode
spring.ai.openai.chat.options.model=deepseek-v4-flash

spring.ai.chat.memory.repository.jdbc.initialize-schema=always 
spring.ai.chat.memory.repository.jdbc.platform=mysql

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ai_demo
spring.datasource.username=root
spring.datasource.password=1111
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

代码

java 复制代码
package com.cry.chatmemorymysql.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepository;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ChatMemoryMysqlController {
    private ChatClient chatClient;
    private JdbcChatMemoryRepository chatMemoryRepository;
    public ChatMemoryMysqlController(ChatClient.Builder builder, JdbcChatMemoryRepository chatMemoryRepository) {
        this.chatMemoryRepository = chatMemoryRepository;
        // 创建聊天存储器
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(chatMemoryRepository)
                .maxMessages(5) // 数据库中同一id,最多保存5条
                .build();
        this.chatClient = builder
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build()) // 使用聊天存储器
                .build();
    }

    @GetMapping("/chat")
    public String chat(@RequestParam(value = "message",defaultValue = "你是谁") String message,@RequestParam(value = "chatId",defaultValue = "1") String chatId) {
        return chatClient.prompt(message)
                // 设置会话id
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .call()
                .content();
    }

    @GetMapping("/chat/list")
    public List<String> chatList() {
        return chatMemoryRepository.findConversationIds();
    }

    @GetMapping("/chat/history")
    public List<Message> chatHistory(@RequestParam(value = "chatId",defaultValue = "1") String chatId) {
        return chatMemoryRepository.findByConversationId(chatId);
    }
}

验证

http://localhost:8080/chat?message=我是ccc&chatId=1
http://localhost:8080/chat?message=我是谁&chatId=1

相关推荐
迅易科技4 小时前
从场景验证到Agent上线:迅易 × WorkBuddy如何帮助企业建设AI能力?
人工智能·ai·腾讯云
神奇霸王龙6 小时前
GB/T 46886 闭环屠夫:5 旗舰多模态 LLM 工业质检实测
人工智能·计算机视觉·ai·开源·ai编程·本地部署
Database_Cool_6 小时前
OLTP 和 OLAP 区别详解:分析型数据库和事务型数据库怎么选(附阿里云 AnalyticDB MySQL 选型指南)
数据库·mysql·阿里云
三声三视6 小时前
uni-app 鸿蒙端传参变成 [object Object]?顺着源码追到 ArkTS router 底层才搞明白
人工智能·ai·uni-app·aigc·ai编程·harmonyos
fthux7 小时前
“装闭”,让装修套路“装”不下去
人工智能·ai·开源·github·open source
Database_Cool_7 小时前
单机 MySQL 迁移到分布式数据库方便吗?阿里云 PolarDB-X 100% MySQL 协议兼容零改造平滑迁移
数据库·分布式·mysql
姜太小白8 小时前
【MySQL】 索引优化实战:解决 WHERE 等值 + IS NULL 查询,TEXT 字段报错 1167 的完整指南
数据库·mysql
doiito8 小时前
【AI 应用】从“外国人味”到地道中文:kokoroi-rs v0.1.2 架构升级深度解析
ai·rust·系统设计
liuxiaowei39 小时前
【绝版教程】新版MySQL DBA高级实战进阶班 MySQL8.0 姜承尧-腾讯数据库总监
数据库·mysql·dba
GPUStack9 小时前
怎么优雅地在GPUStack上使用minerU?
ai·大模型·llm·gpu·vllm·gpu集群·gpustack