|
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 java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Component
@RequiredArgsConstructor
public class RedisChatHistoryRepository implements ChatHistoryRepository {
private final RedisTemplate<String, Object> redisTemplate;
// Redis key前缀
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 save(String type, String chatId, Long userId) {
// 保存会话信息
String sessionKey = CHAT_SESSION_PREFIX + chatId;
Map<String, Object> 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);
// 设置过期时间为30天
redisTemplate.expire(sessionKey, 30, TimeUnit.DAYS);
// 将chatId添加到用户的聊天历史列表中
String historyKey = CHAT_HISTORY_PREFIX + userId + ":" + type;
redisTemplate.opsForSet().add(historyKey, chatId);
// 设置过期时间为30天
redisTemplate.expire(historyKey, 30, TimeUnit.DAYS);
}
/**
* 获取用户的会话ID列表
*/
@Override
public List<String> getChatIds(Long userId, String type) {
String historyKey = CHAT_HISTORY_PREFIX + userId + ":" + type;
Set<Object> chatIds = redisTemplate.opsForSet().members(historyKey);
if (chatIds == null || chatIds.isEmpty()) {
return Collections.emptyList();
}
return chatIds.stream()
.map(Object::toString)
.collect(Collectors.toList());
}
/**
* 保存聊天消息
*/
@Override
public void saveMessage(String chatId, String message, String sender) {
String messagesKey = CHAT_MESSAGES_PREFIX + chatId;
// 创建消息对象
Map<String, Object> messageInfo = new HashMap<>();
messageInfo.put("content", message);
messageInfo.put("sender", sender);
messageInfo.put("timestamp", System.currentTimeMillis());
// 使用JSON格式保存消息
ObjectMapper objectMapper = new ObjectMapper();
try {
String jsonMessage = objectMapper.writeValueAsString(messageInfo);
redisTemplate.opsForList().rightPush(messagesKey, jsonMessage);
} catch (JsonProcessingException e) {
e.printStackTrace();
// 如果JSON序列化失败,使用原始消息
redisTemplate.opsForList().rightPush(messagesKey, message);
}
// 设置过期时间为30天
redisTemplate.expire(messagesKey, 30, TimeUnit.DAYS);
// 更新会话的最后更新时间
String sessionKey = CHAT_SESSION_PREFIX + chatId;
redisTemplate.opsForHash().put(sessionKey, "lastUpdateTime", System.currentTimeMillis());
// 确保会话信息也有过期时间
redisTemplate.expire(sessionKey, 30, TimeUnit.DAYS);
}
/**
* 获取聊天消息历史
*/
@Override
public List<String> getMessages(String chatId) {
String messagesKey = CHAT_MESSAGES_PREFIX + chatId;
List<Object> messages = redisTemplate.opsForList().range(messagesKey, 0, -1);
if (messages == null || messages.isEmpty()) {
return Collections.emptyList();
}
return messages.stream()
.map(Object::toString)
.collect(Collectors.toList());
}
/**
* 删除会话
*/
@Override
public void deleteChat(Long userId, String type, String chatId) {
// 从用户的聊天历史列表中删除
String historyKey = CHAT_HISTORY_PREFIX + userId + ":" + type;
redisTemplate.opsForSet().remove(historyKey, chatId);
// 删除会话信息
String sessionKey = CHAT_SESSION_PREFIX + chatId;
redisTemplate.delete(sessionKey);
// 删除聊天消息
String messagesKey = CHAT_MESSAGES_PREFIX + chatId;
redisTemplate.delete(messagesKey);
}
/**
* 获取会话信息
*/
@Override
public Map<Object, Object> getSessionInfo(String chatId) {
String sessionKey = CHAT_SESSION_PREFIX + chatId;
return redisTemplate.opsForHash().entries(sessionKey);
}
}
|