惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
B
Blog
aimingoo的专栏
aimingoo的专栏
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
月光博客
月光博客
H
Help Net Security
V
Visual Studio Blog
量子位
A
About on SuperTechFans
博客园 - Franky
人人都是产品经理
人人都是产品经理
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
P
Proofpoint News Feed
MongoDB | Blog
MongoDB | Blog

博客园 - cn2025

K8s -sentinel-dashboard【nacos版本】集 20260815 kubeSphere【ks-controller-manager-webhook-cert】证书 20260814 K8s -nacos集 20260813 K8s - 安装部署redis集群-哨兵sentinels集(支持从K8s外部访问)20260812 k8s-deployment发布测试(pv-pvc-deployment-service) 20260810 K8s - 安装部署Kafka、Zookeeper集群教程(支持从K8s外部访问)20260808 k8s-关机及启动脚本工具 【kubeSphere发布ruoyi-pro前端】工具脚本20260731 【k8s】 etcd服务端及客户端版本及快照【定时】备份 20260730 harbor【https启用】及k8节点部证书20260728 kube-flannel.yml k8s集群-安装helm 【kubeShpere】 官网 20260710 kubesphere-KDP 工具脚本【kubeSphere发布ruoyi-pro前端】20260720 HbuilderX 内置终端转为 gitBash 20260720 kubeSphere发布ruoyi-pro后端-用到脚本 kubeSphere发布ruoyi-web前端 20260711 kubeSphere发布ruoyi-pro后端 k8s集群-kubeShpere 20260710 安装Helm 20260710 k8s-portainer docker 镜像查询 k8集群一键重置 docker run OceanBase spring ai alibaba doc AI2.0 【多模态】 20260615 世界只有一个墨脱 AI2.0 【Mcp-client】 20260611 AI2.0 【Mcp-server】 20260611 GoLand 配Go SDK
ChatmemoryMax 历史对话长度20260507
cn2025 · 2026-05-07 · via 博客园 - cn2025

1、pom

<properties>
<java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>3.2.0</spring-boot.version>
<spring-ai.version>1.0.0</spring-ai.version>
<spring-ai-alibaba.version>1.0.0.2</spring-ai-alibaba.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 阿里云通义千问(DashScope)starter -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>
<!--对话记忆 chat-memory-->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-autoconfigure-model-chat-memory</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 统一管理Spring AI依赖版本 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-bom</artifactId>
<version>${spring-ai-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- Spring AI 里程碑/快照仓库(必须配置,否则依赖无法下载) -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>

2、yml


#server.port=18081
#spring.ai.dashscope.api-key="sk-72d9fd311cde487eb948bcd999ea4a65"
#spring.ai.dashscope.chat.options.model= sk-8718a83408d7443b9544cdfbf259280f
#sk-72d9fd311cde487eb948bcd999ea4a65
server:
port: 18081
spring:
ai:
dashscope:
api-key: sk-8718a83408d7443bxxxxxxx
logging: #####日志级别
level:
   org.springframework.ai.chat.client.advisor: debug


3、config
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class config {

@Bean
ChatMemory chatMemoryMax(ChatMemoryRepository chatMemoryRepository) {
return MessageWindowChatMemory
.builder()
// 自定义最大消息数,覆盖默认的20条 (2 轮用户 + 助手对话)
//保留最近 2 条消息。若超出则删除最早的消息
.maxMessages(2)
// 绑定持久化仓库(支持多用户会话隔离)
.chatMemoryRepository(chatMemoryRepository)
.build();
}
}


4、controller
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequestMapping("/openai")
@ResponseBody
@Controller
public class ChatMemoryController {

@Autowired
//保留最近 10 条消息。若超出则删除最早的消息
private ChatMemory chatMemoryMax;

/**
* 基于 ChatMemory max 历史对话长度
*/
@GetMapping("/simple/chatmemorymax")
public String chatmemory4 () {
// 1. 创建对话记忆(滑动窗口实现)
// ChatMemory chatMemory = MessageWindowChatMemory.builder()
// // 自定义最大消息数,覆盖默认的20条 (2 轮用户 + 助手对话)
// .maxMessages(10) //保留最近 2 条消息。若超出则删除最早的消息
// //对话历史存储
// .chatMemoryRepository(chatMemoryRepository)
// .build();
String conversationId = "lyd001"; // 对话唯一标识

// First interaction
UserMessage userMessage1 = new UserMessage("我叫永乐帝");
chatMemory.add(conversationId, userMessage1);
ChatResponse response1 = chatModel.call(new Prompt(chatMemoryMax.get(conversationId)));
chatMemory.add(conversationId, response1.getResult().getOutput());
String content1 = String.valueOf(response1.getResult().getOutput());
System.out.println("【content1】:" + content1);
//Second interaction
UserMessage userMessage2 = new UserMessage("我叫什么?");
chatMemory.add(conversationId, userMessage2);
ChatResponse response2 = chatModel.call(new Prompt(chatMemoryMax.get(conversationId)));
chatMemory.add(conversationId, response2.getResult().getOutput());
String content2 = String.valueOf(response2.getResult().getOutput());
System.out.println("【content2】:" + content2);
//Three interaction
UserMessage userMessage3 = new UserMessage("我叫什么?");
chatMemory.add(conversationId, userMessage3);
ChatResponse response3 = chatModel.call(new Prompt(chatMemoryMax.get(conversationId)));
chatMemory.add(conversationId, response3.getResult().getOutput());
String content3 = String.valueOf(response3.getResult().getOutput());
System.out.println("【content3】:" + content3);
printChatHistory(chatMemoryMax.get(conversationId));

return "【content1】:"+content1+"------------" +"【content2】:"+content2
+"------------" +"【content3】:"+content3+
";------------------------" +
"【基于 ChatMemoryMax(2)历史对话长度的历史信息】"+MessageChatHistory(chatMemoryMax.get(conversationId));
}

// 封装:打印当前会话所有历史消息
private void printChatHistory(List<Message> messageList) {
System.out.println("----------------会话所有历史消息开始------------------------");
for (int i = 0; i < messageList.size(); i++) {
Message msg = messageList.get(i);
System.out.println("-------第"+(i+1)+"条["+msg.getMessageType()+"]:" + msg.getText());
}
System.out.println("-----------------会话所有历史消息结束-----------------------");
}

private String MessageChatHistory(List<Message> messageList) {
String restr="";
System.out.println("----------------会话所有历史消息开始------------------------");
for (int i = 0; i < messageList.size(); i++) {
Message msg = messageList.get(i);
restr+="-------第【"+(i+1)+"】条["+msg.getMessageType()+"]:" + msg.getText();
}
System.out.println("-----------------会话所有历史消息结束-----------------------");
return restr;
}


}

5、http://localhost:18081/openai/simple/chatmemorymaxcontent1\content2\content3 三轮对话, 限两轮历史对话记录.maxMessages(2)

image