This commit is contained in:
2025-08-19 23:00:07 +08:00

View File

@@ -16,6 +16,8 @@ import okhttp3.*;
import com.srs.common.core.domain.AjaxResult; // ✅ RuoYi 的返回结果类
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@@ -83,6 +85,16 @@ public class AiChatController extends BaseController {
*/
private static final String DIFY_FILES_URL = "http://47.112.118.149:8100/v1/files/upload";
/**
* Redis中会话ID的key前缀
*/
private static final String CONVERSATION_ID_CACHE_PREFIX = "dify:conversation:id:";
/**
* Redis中会话ID的过期时间小时
*/
private static final int CONVERSATION_ID_CACHE_EXPIRE_HOURS = 1;
/**
* HTTP客户端实例
* 配置了5分钟的读取超时时间用于与Dify API进行通信
@@ -94,6 +106,12 @@ public class AiChatController extends BaseController {
.retryOnConnectionFailure(true)
.build();
/**
* Redis模板用于缓存会话ID
*/
@Autowired
private StringRedisTemplate stringRedisTemplate;
/** 为本次请求设置 “总超时”(含连接/读写),避免无限挂起 */
private Response execWithTimeouts(Request req, int callSecs, int readSecs, int writeSecs) throws IOException {
OkHttpClient shortClient = client.newBuilder()
@@ -486,19 +504,29 @@ public class AiChatController extends BaseController {
@PreAuthorize("@ss.hasPermi('cph:teacher:list')")
@GetMapping("/getMessagesToAdmin")
public AjaxResult getMessagesToAdmin(@RequestParam String user,
@RequestParam(required = false) String firstId,
@RequestParam(defaultValue = "20") int limit,
@RequestParam(defaultValue = "-updated_at") String sortBy) {
@RequestParam(required = false) String firstId,
@RequestParam(defaultValue = "20") int limit,
@RequestParam(defaultValue = "-updated_at") String sortBy) {
try {
List<ConversationDTO> conversations = getConversations(user);
// 首先尝试从Redis缓存中获取会话ID
String conversationId = getCachedConversationId(user);
if (conversations == null || conversations.isEmpty()) {
return AjaxResult.error("暂无会话记录");
// 如果Redis缓存中没有会话ID则使用原来的方法获取
if (conversationId == null) {
List<ConversationDTO> conversations = getConversations(user);
if (conversations == null || conversations.isEmpty()) {
return AjaxResult.error("暂无会话记录");
}
conversationId = conversations.get(0).getId();
// 将获取到的会话ID缓存到Redis中
cacheConversationId(user, conversationId);
}
String conversation_id = conversations.get(0).getId();
Map<String, Object> result = getConversationHistoryMessages(conversation_id, user, firstId, limit);
Map<String, Object> result = getConversationHistoryMessages(conversationId, user, firstId, limit);
AjaxResult successResult = success(result);
return successResult;
@@ -514,21 +542,30 @@ public class AiChatController extends BaseController {
// 权限标识为学生
@GetMapping("/getMessagesToUser")
public AjaxResult getMessagesToUser(@RequestParam(required = false) String firstId,
@RequestParam(defaultValue = "20") int limit,
@RequestParam(defaultValue = "-updated_at") String sortBy) {
@RequestParam(defaultValue = "20") int limit,
@RequestParam(defaultValue = "-updated_at") String sortBy) {
try {
String user = SecurityUtils.getLoginUser().getUsername();
List<ConversationDTO> conversations = getConversations(user);
// 首先尝试从Redis缓存中获取会话ID
String conversationId = getCachedConversationId(user);
if (conversations == null || conversations.isEmpty()) {
return AjaxResult.error("暂无会话记录");
// 如果Redis缓存中没有会话ID则使用原来的方法获取
if (conversationId == null) {
List<ConversationDTO> conversations = getConversations(user);
if (conversations == null || conversations.isEmpty()) {
return AjaxResult.error("暂无会话记录");
}
conversationId = conversations.get(0).getId();
// 将获取到的会话ID缓存到Redis中
cacheConversationId(user, conversationId);
}
String conversation_id = conversations.get(0).getId();
Map<String, Object> result = getConversationHistoryMessages(conversation_id, user, firstId, limit);
Map<String, Object> result = getConversationHistoryMessages(conversationId, user, firstId, limit);
AjaxResult successResult = success(result);
return successResult;
@@ -541,6 +578,62 @@ public class AiChatController extends BaseController {
}
}
/**
* 从Redis缓存中获取用户的会话ID
*
* @param user 用户名
* @return 会话ID如果不存在则返回null
*/
private String getCachedConversationId(String user) {
try {
// 参数校验
if (user == null || user.trim().isEmpty()) {
return null;
}
user = user.trim();
String cacheKey = CONVERSATION_ID_CACHE_PREFIX + user;
// 从Redis中获取会话ID
String conversationId = stringRedisTemplate.opsForValue().get(cacheKey);
return conversationId;
} catch (Exception e) {
return null;
}
}
/**
* 将会话ID与用户绑定并存储到Redis中
*
* @param user 用户名
* @param conversationId 会话ID
*/
private void cacheConversationId(String user, String conversationId) {
try {
// 参数校验
if (user == null || user.trim().isEmpty()) {
return;
}
if (conversationId == null || conversationId.trim().isEmpty()) {
return;
}
user = user.trim();
conversationId = conversationId.trim();
// 将用户与会话ID绑定存储到Redis中
String cacheKey = CONVERSATION_ID_CACHE_PREFIX + user;
stringRedisTemplate.opsForValue().set(
cacheKey,
conversationId,
Duration.ofHours(CONVERSATION_ID_CACHE_EXPIRE_HOURS));
} catch (Exception e) {
System.out.println("绑定会话ID时发生错误: " + e.getMessage());
}
}
/*
* 获取会话列表
*/
@@ -570,7 +663,6 @@ public class AiChatController extends BaseController {
// 读取响应体
String responseBodyString = response.body().string();
System.out.println("Raw Response: " + responseBodyString); // 打印原始数据
JsonNode rootNode = mapper.readTree(responseBodyString);
// 提取 data 数组