基于SpringBoot3与SpringAI整合,利用Redis存储实现具备记忆功能的AI助手,支持用户级会话隔离与30天对话持久化,技术栈包括Java17、MyBatisPlus、MySQL,通过配置消息序列化与仓库接口完成核心功能。
最近在做一个智能图片社区项目,用户希望有一个能记住对话上下文的AI助手。经过技术选型,最终敲定了 Spring Boot 3 + Spring AI + Redis 这套方案。下面就把整个实现过程拆开揉碎了讲清楚,从环境准备到核心代码,再到测试验证,一步不落。
本教程详细介绍如何使用 Spring Boot 3 整合 Spring AI 实现一个具有记忆功能的 AI 助手。该实现使用 Redis 作为存储介质,支持用户级别的会话隔离和 30 天的对话历史持久化。
长期稳定更新的攒劲资源: >>>点此立即查看<<<

确保 JA VA_HOME 和 MA VEN_HOME 已正确配置。
使用 Spring Initializr 创建项目:
在 pom.xml 文件中添加以下依赖:
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-redis
com.baomidou
mybatis-plus-boot-starter
3.5.5
com.mysql
mysql-connector-j
runtime
org.springframework.ai
spring-ai-openai
1.0.0
cn.dev33
sa-token-spring-boot-starter
1.38.1
com.fasterxml.jackson.core
jackson-databind
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
application.yml)创建 src/main/resources/application.yml 文件,配置应用信息:
server:
port: 9527
servlet:
context-path: /api
spring:
application:
name: smart-pic-community-backend
# Redis 配置
data:
redis:
database: 2
host: localhost
port: 6379
timeout: 5000
# 数据库配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/smart_pic_community
username: root
password: your_password
# Spring AI 配置
ai:
openai:
base-url: https://api.deepseek.com/ # 使用 DeepSeek API
api-key: your_api_key
chat:
options:
model: deepseek-chat
RedisConfiguration.ja va)创建 Redis 配置类,确保正确序列化对象:
package com.spc.smartpiccommunitybackend.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@Slf4j
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
log.info("开始创建redis模板对象...");
RedisTemplate redisTemplate = new RedisTemplate<>();
// 设置连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用 StringRedisSerializer 来序列化和反序列化 redis 的 key
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key 采用 String 的序列化方式
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// 使用 Jackson2JsonRedisSerializer 来序列化和反序列化 redis 的 value
Jackson2JsonRedisSerializer
这里有几个关键点需要注意:
Jackson2JsonRedisSerializer 而不是 StringRedisSerializer,可以避免 ClassCastException创建消息视图对象,用于前端展示:
package com.spc.smartpiccommunitybackend.model.vo.ai;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.ai.chat.messages.Message;
@NoArgsConstructor
@Data
public class MessageVO {
private String role;
private String content;
public MessageVO(Message message) {
this.role = switch (message.getMessageType()) {
case USER -> "user";
case ASSISTANT -> "assistant";
case SYSTEM -> "system";
default -> "";
};
this.content = message.getText();
}
}
功能说明:
Message 对象转换为前端可识别的格式创建可序列化的消息对象,用于 Redis 存储:
package com.spc.smartpiccommunitybackend.model.entity.ai;
import lombok.Data;
import lombok.NoArgsConstructor;
import ja va.io.Serializable;
@Data
@NoArgsConstructor
public class SerializableMessage implements Serializable {
private static final long serialVersionUID = 1L;
private String role;
private String content;
private String messageType;
private Long timestamp;
public SerializableMessage(String role, String content, String messageType) {
this.role = role;
this.content = content;
this.messageType = messageType;
this.timestamp = System.currentTimeMillis();
}
public SerializableMessage(String role, String content) {
this(role, content, "user");
}
}
功能说明:
Serializable 接口,支持 Redis 序列化ChatHistoryRepository.ja va)创建聊天历史仓库接口:
package com.spc.smartpiccommunitybackend.repository;
import ja va.util.List;
import ja va.util.Map;
public interface ChatHistoryRepository {
/** 保存会话记录 */
void sa ve(String type, String chatId, Long userId);
/** 获取用户的会话ID列表 */
List getChatIds(Long userId, String type);
/** 保存聊天消息 */
void sa veMessage(String chatId, String message, String sender);
/** 获取聊天消息历史 */
List getMessages(String chatId);
/** 删除会话 */
void deleteChat(Long userId, String type, String chatId);
/** 获取会话信息 */
Map
RedisChatHistoryRepository.ja va)实现基于 Redis 的聊天历史仓库:
package com.spc.smartpiccommunitybackend.repository;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import ja va.util.*;
import ja va.util.concurrent.TimeUnit;
import ja va.util.stream.Collectors;
@Component
@RequiredArgsConstructor
public class RedisChatHistoryRepository implements ChatHistoryRepository {
private final RedisTemplate redisTemplate;
private static final String CHAT_HISTORY_PREFIX = "chat:history:";
private static final String CHAT_SESSION_PREFIX = "chat:session:";
private static final String CHAT_MESSAGES_PREFIX = "chat:messages:";
@Override
public void sa ve(String type, String chatId, Long userId) {
String sessionKey = CHAT_SESSION_PREFIX + chatId;
Map sessionInfo = new HashMap<>();
sessionInfo.put("userId", String.valueOf(userId));
sessionInfo.put("type", type);
sessionInfo.put("createTime", System.currentTimeMillis());
sessionInfo.put("lastUpdateTime", System.currentTimeMillis());
redisTemplate.opsForHash().putAll(sessionKey, sessionInfo);
redisTemplate.expire(sessionKey, 30, TimeUnit.DAYS);
String historyKey = CHAT_HISTORY_PREFIX + userId + ":" + type;
redisTemplate.opsForSet().add(historyKey, chatId);
redisTemplate.expire(historyKey, 30, TimeUnit.DAYS);
}
@Override
public List getChatIds(Long userId, String type) {
String historyKey = CHAT_HISTORY_PREFIX + userId + ":" + type;
Set
这段实现有几个设计要点:
RedisChatMemory.ja va)实现基于 Redis 的聊天记忆,支持 Spring AI 的 ChatMemory 接口:
package com.spc.smartpiccommunitybackend.config;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import ja va.util.ArrayList;
import ja va.util.List;
import ja va.util.concurrent.TimeUnit;
@Component
public class RedisChatMemory implements ChatMemory {
private final RedisTemplate redisTemplate;
private static final String MEMORY_KEY_PREFIX = "chat:memory:";
private static final long EXPIRATION_DAYS = 30;
public RedisChatMemory(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public void add(String key, List messages) {
for (Message message : messages) {
addMessage(key, message);
}
}
@Override
public List get(String key, int maxCount) {
List messages = getMessages(key);
if (maxCount > 0 && messages.size() > maxCount) {
return messages.subList(messages.size() - maxCount, messages.size());
}
return messages;
}
@Override
public void clear() {
// 清理所有会话记忆,谨慎使用
}
public void addMessage(String chatId, Message message) {
String key = MEMORY_KEY_PREFIX + chatId;
redisTemplate.opsForList().rightPush(key, message);
redisTemplate.expire(key, EXPIRATION_DAYS, TimeUnit.DAYS);
}
public List getMessages(String chatId) {
String key = MEMORY_KEY_PREFIX + chatId;
List objects = redisTemplate.opsForList().range(key, 0, -1);
List messages = new ArrayList<>();
if (objects != null) {
for (Object obj : objects) {
if (obj instanceof Message) {
messages.add((Message) obj);
}
}
}
return messages;
}
public void clear(String chatId) {
String key = MEMORY_KEY_PREFIX + chatId;
redisTemplate.delete(key);
}
}
注意:
ChatMemory 接口以支持 Spring AI 的消息记忆功能CommonConfiguration.ja va)配置 Spring AI 的 ChatClient:
package com.spc.smartpiccommunitybackend.config;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CommonConfiguration {
@Bean
public ChatClient chatClient(OpenAiChatModel openAiChatModel, ChatMemory chatMemory) {
return ChatClient.builder(openAiChatModel)
.defaultAdvisors(
new SimpleLoggerAdvisor(),
new MessageChatMemoryAdvisor(chatMemory)
)
.build();
}
}
这里的关键是使用 MessageChatMemoryAdvisor 来启用聊天记忆功能,SimpleLoggerAdvisor 用于记录交互日志,方便调试。
ChatController.ja va)实现聊天控制器,处理 AI 对话请求:
package com.spc.smartpiccommunitybackend.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spc.smartpiccommunitybackend.repository.RedisChatHistoryRepository;
import com.spc.smartpiccommunitybackend.service.UserService;
import com.spc.smartpiccommunitybackend.utils.ErrorCode;
import com.spc.smartpiccommunitybackend.utils.ThrowUtils;
import com.spc.smartpiccommunitybackend.pojo.User;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.beans.factory.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import ja vax.servlet.http.HttpServletRequest;
import ja va.io.IOException;
import ja va.util.ArrayList;
import ja va.util.List;
@RestController
@RequestMapping("/ai")
public class ChatController {
private final ChatClient chatClient;
private final RedisChatHistoryRepository chatHistoryRepository;
@Resource
private UserService userService;
public ChatController(ChatClient chatClient, RedisChatHistoryRepository chatHistoryRepository) {
this.chatClient = chatClient;
this.chatHistoryRepository = chatHistoryRepository;
}
@RequestMapping(value = "/chat", produces = "text/html;charset=UTF-8")
public Flux chat(@RequestParam(defaultValue = "讲个笑话") String prompt,
String chatId,
HttpServletRequest request) {
User loginUser = userService.getLoginUser(request);
ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
Long userId = loginUser.getId();
chatHistoryRepository.sa ve("chat", chatId, userId);
List messages = new ArrayList<>();
SystemMessage systemMessage = new SystemMessage(
"你是一个智能图片社区的AI助手,名为虹小智。请用友好、专业的语气回答用户问题," +
"提供关于图片社区的相关信息和帮助。");
messages.add(systemMessage);
List historyMessages = chatHistoryRepository.getMessages(chatId);
ObjectMapper objectMapper = new ObjectMapper();
for (String messageStr : historyMessages) {
try {
JsonNode node = objectMapper.readTree(messageStr);
String sender = node.get("sender").asText();
String content = node.get("content").asText();
if ("user".equals(sender)) {
messages.add(new UserMessage(content));
} else if ("ai".equals(sender)) {
messages.add(new AssistantMessage(content));
}
} catch (IOException e) {
e.printStackTrace();
}
}
messages.add(new UserMessage(prompt));
chatHistoryRepository.sa veMessage(chatId, prompt, "user");
return chatClient.stream(messages)
.doOnNext(response -> {
chatHistoryRepository.sa veMessage(chatId, response, "ai");
});
}
}
几个值得注意的设计:
Flux 实现流式响应,提高用户体验ChatHistoryController.ja va)实现聊天历史控制器,处理聊天历史的获取和删除:
package com.spc.smartpiccommunitybackend.controller;
import com.spc.smartpiccommunitybackend.repository.RedisChatHistoryRepository;
import com.spc.smartpiccommunitybackend.service.UserService;
import com.spc.smartpiccommunitybackend.utils.ErrorCode;
import com.spc.smartpiccommunitybackend.utils.ThrowUtils;
import com.spc.smartpiccommunitybackend.pojo.User;
import org.springframework.web.bind.annotation.*;
import ja vax.servlet.http.HttpServletRequest;
import ja va.util.List;
@RestController
@RequestMapping("/ai/history")
public class ChatHistoryController {
private final RedisChatHistoryRepository chatHistoryRepository;
private final UserService userService;
public ChatHistoryController(RedisChatHistoryRepository chatHistoryRepository, UserService userService) {
this.chatHistoryRepository = chatHistoryRepository;
this.userService = userService;
}
@GetMapping("/{type}")
public List getChatHistory(@PathVariable String type, HttpServletRequest request) {
User loginUser = userService.getLoginUser(request);
ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
Long userId = loginUser.getId();
return chatHistoryRepository.getChatIds(userId, type);
}
@DeleteMapping("/{type}/{chatId}")
public boolean deleteChatHistory(@PathVariable String type, @PathVariable String chatId, HttpServletRequest request) {
User loginUser = userService.getLoginUser(request);
ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
Long userId = loginUser.getId();
chatHistoryRepository.deleteChat(userId, type, chatId);
return true;
}
}
同样,这里验证了用户登录状态,确保只能操作自己的聊天历史。接口设计简洁,方便前端调用。
http://localhost:9527/api/ai/chatprompt=你好&chatId=test123 测试 AI 响应http://localhost:9527/api/ai/chatprompt=你好,我叫张三&chatId=test123http://localhost:9527/api/ai/chatprompt=你知道我叫什么名字吗?&chatId=test123GET http://localhost:9527/api/ai/history/chatDELETE http://localhost:9527/api/ai/history/chat/test123侠游戏发布此文仅为了传递信息,不代表侠游戏网站认同其观点或证实其描述