@@ -88,8 +88,20 @@ public class AiChatController extends BaseController {
* 配置了5分钟的读取超时时间, 用于与Dify API进行通信
*/
private final OkHttpClient client = new OkHttpClient . Builder ( )
. read Timeout( Duration . ofMinute s ( 5 ) )
. connect Timeout( Duration . ofSecond s ( 5 ) ) // 建连超时
. readTimeout ( Duration . ofSeconds ( 12 ) ) // 读超时(服务端应在此内有数据返回)
. writeTimeout ( Duration . ofSeconds ( 12 ) ) // 写超时
. retryOnConnectionFailure ( true )
. build ( ) ;
/** 为本次请求设置 “总超时”(含连接/读写),避免无限挂起 */
private Response execWithTimeouts ( Request req , int callSecs , int readSecs , int writeSecs ) throws IOException {
OkHttpClient shortClient = client . newBuilder ( )
. callTimeout ( java . time . Duration . ofSeconds ( callSecs ) ) // 整次调用最大时长
. readTimeout ( java . time . Duration . ofSeconds ( readSecs ) ) // 读超时(这段时间没有字节到达就超时)
. writeTimeout ( java . time . Duration . ofSeconds ( writeSecs ) ) // 写超时
. build ( ) ;
return shortClient . newCall ( req ) . execute ( ) ;
}
/**
* JSON对象映射器
@@ -539,7 +551,7 @@ public class AiChatController extends BaseController {
. build ( ) ;
// 执行请求
try ( Response response = client . newCall ( request ) . execute ( ) ) {
try ( Response response = execWithTimeouts ( request , 8 , 8 , 8 ) ) {
if ( ! response . isSuccessful ( ) ) {
throw new IOException ( " Dify API 请求失败: " + response . code ( ) + " " + response . message ( ) ) ;
}
@@ -580,7 +592,7 @@ public class AiChatController extends BaseController {
}
public List < ConversationDTO > getConversations ( String user , String lastId ) throws IOException {
return getConversations ( user , lastId , 0 , null ) ;
return getConversations ( user , lastId , 1 , " -updated_at " ) ;
}
public List < ConversationDTO > getConversations ( String user , Integer limit , String sortBy ) throws IOException {
@@ -623,7 +635,7 @@ public class AiChatController extends BaseController {
. get ( )
. build ( ) ;
try ( Response response = client . newCall ( request ) . execute ( ) ) {
try ( Response response = execWithTimeouts ( request , 8 , 8 , 8 ) ) {
if ( ! response . isSuccessful ( ) ) {
String body = response . body ( ) ! = null ? response . body ( ) . string ( ) : " No body " ;