fix: 修复因为单例 OkHttpClient 的使用导致ws连接失败的bug

11111
winter 1 year ago
parent f2e0c0b19e
commit ab2aaa1757

@ -32,7 +32,7 @@ import java.util.concurrent.TimeUnit;
public class SparkGptClient implements InitializingBean {
@Resource
private SparkGptProperties sparkGptProperties;
private OkHttpClient okHttpClient;
// private OkHttpClient okHttpClient;
private String authUrl;
/**
@ -46,12 +46,12 @@ public class SparkGptClient implements InitializingBean {
this.authUrl = authUrl.replace("http://", "ws://").replace("https://", "wss://");
log.info("[SPARK CHAT] 鉴权 endpoint : {}", this.authUrl);
// 初始化 okHttpClient
this.okHttpClient = new OkHttpClient()
.newBuilder()
.connectTimeout(90, TimeUnit.SECONDS)
.readTimeout(90, TimeUnit.SECONDS) // sse 接口的 readTimeout 不能设置小了
.writeTimeout(90, TimeUnit.SECONDS)
.build();
// this.okHttpClient = new OkHttpClient()
// .newBuilder()
// .connectTimeout(90, TimeUnit.SECONDS)
// .readTimeout(90, TimeUnit.SECONDS) // sse 接口的 readTimeout 不能设置小了
// .writeTimeout(90, TimeUnit.SECONDS)
// .build();
}
/**
@ -64,6 +64,12 @@ public class SparkGptClient implements InitializingBean {
// 设置请求参数
listener.setRequestJson(param.toJsonParams());
log.info("[SPARK CHAT] 请求参数 {}", JSONUtil.parseObj(param.toJsonParams()).toStringPretty());
OkHttpClient okHttpClient = new OkHttpClient()
.newBuilder()
.connectTimeout(90, TimeUnit.SECONDS)
.readTimeout(90, TimeUnit.SECONDS) // sse 接口的 readTimeout 不能设置小了
.writeTimeout(90, TimeUnit.SECONDS)
.build();
okHttpClient.newWebSocket(request, listener);
} catch (Exception e) {
log.error("[SPARK CHAT] Spark AI 请求异常: {}", e.getMessage());

@ -63,8 +63,9 @@ public class SparkGptStreamListener extends WebSocketListener {
}
// 推送回答 segment
String msgSegment = sparkChatResponse.getPayload().getChoices().getText().get(0).getContent();
// 处理消息格式(空格和换行符)
msgSegment = StrUtil.replace(msgSegment, " ", " ").replaceAll("\n", "&#92n");
// 处理消息格式(空格和换行符)
// msgSegment = StrUtil.replace(msgSegment, " ", " ").replaceAll("\n", "&#92n");
msgSegment = StrUtil.replace(msgSegment, " ", "&#32;").replaceAll("\n", "<br/>");
answer += msgSegment;
SseHelper.send(sseEmitter, msgSegment);

@ -93,14 +93,14 @@ public class ChatMessageServiceImpl implements ChatMessageService {
if (ObjectUtils.isNotEmpty(context)) {
HistoryCache.putContext(sessionId, context);
}
}
// convert DB Message to Spark Message
context.forEach(item -> {
paramMessages.add(SparkChatRequestParam.Message.ofUser(item.getUserText()));
paramMessages.add(SparkChatRequestParam.Message.ofAssistant(item.getGptText()));
});
}
}
paramMessages.add(SparkChatRequestParam.Message.ofUser(prompt));
return paramMessages;
}

Loading…
Cancel
Save