main
daixiaoyi 2 months ago
parent 20930e7122
commit 62224df3a5

@ -85,6 +85,14 @@
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>

@ -55,14 +55,7 @@ public class ChatController {
}
@GetMapping(value="/stream",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<Map<String, String>>> test2(@RequestParam("query") String query) {
public Flux<ServerSentEvent<Map<String, String>>> stream(@RequestParam("query") String query) {
return chatService.streamingMessage(query);
}
@GetMapping(value = "/webflux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> chatWebFlux() {
String string = ResourceUtil.readUtf8Str("classpath:static/test.txt");
String[] stringArray = StrUtil.split(string, 1);
return Flux.just(stringArray).delayElements(Duration.ofMillis(50));
}
}

@ -76,26 +76,28 @@ public class ChatServiceImpl implements IChatService {
Map<String, String> map = new HashMap<>();
map.put("event", response.getEvent());
if (response.getEvent().equals("message") && response.getAnswer() != null) {
String voiceBaseId = UUID.randomUUID().toString();
//遍历answer中的每一个字符判断是否为标点符号如果是说明是句子的结尾将标点符号前的文本拼接到sentence中并打印然后清空sentence如果标点符号后还有文本将文本拼接到sentence中
for (char ch : response.getAnswer().toCharArray()) {
sentence.append(ch);
if (ch == '。' || ch == '' || ch == '' || ch == '' || ch == '、' || ch == '' || ch == '' || ch == '“' || ch == '”') { // Check for punctuation marks
log.info(sentence.toString());
TtsResultDTO ttsResultDTO = TtsUtil.ttsTransform(sentence.toString());
String voiceBaseId = UUID.randomUUID().toString();
voiceCache.put(voiceBaseId, ttsResultDTO.getAudio());
map.put("audioId", voiceBaseId);
sentence.setLength(0); // Clear the sentence
return ServerSentEvent.builder(map).build();
}
}
if (response.getEvent().equals("message_end") && !sentence.isEmpty()) {
log.info(sentence.toString());
TtsResultDTO ttsResultDTO = TtsUtil.ttsTransform(sentence.toString());
String voiceBaseId = UUID.randomUUID().toString();
voiceCache.put(voiceBaseId, ttsResultDTO.getAudio());
map.put("audioId", voiceBaseId);
}
return ServerSentEvent.builder(map).build();
}
}
return ServerSentEvent.builder(map).build();
});
}

@ -1,3 +0,0 @@
SpringBoot+WebFlux通过流式响应实现类似ChatGPT的打字机效果
突然间想用Java实现一下像ChatGPT一样的打字机输出效果但是网上搜了相关教程感觉都不够满意。
这里贴一下自己的实现,为中文互联网做一点小小的贡献
Loading…
Cancel
Save