介绍
用于构建基于 WebFlux 的响应式 Web 应用程序。集成了 Spring WebFlux 模块,支持响应式编程模型,构建非阻塞、异步的 Web 应用。WebFlux 使用了非阻塞的异步模型,能够更好地处理高并发请求。适合需要实时数据推送的应用场景。
WebClient 是 Spring WebFlux 中用于创建 WebClient 实例的构建器方法。用于发起 HTTP 请求的非阻塞、响应式的客户端,可以与 Web 服务进行交互,支持异步和响应式编程模型。
讯飞星火
官方文档:https://www.xfyun.cn/doc/spark/X1http.html
接口地址:https://spark-api-open.xf-yun.com/v2/chat/completions
效果图
流式异步返回数据
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
构建请求体
/**
* 构建消息体
* @param userId 用户的唯一id,表示一个用户,user_123456
* @param text 问题内容
* @return
*/
private JSONObject builderBody(String userId,String text){
// 创建最外层的JSON对象并填充字段
JSONObject jsonObject = new JSONObject();
jsonObject.put("user", userId);
jsonObject.put("model", "x1");
jsonObject.put("stream", true);
jsonObject.put("max_tokens", 4096);
// 创建单个消息的JSON对象
JSONObject messageObject = new JSONObject();
messageObject.put("role", "user");
messageObject.put("content", text);
messageObject.put("temperature", "0.5");
// 历史记录
JSONObject test = new JSONObject();
test.put("role", "user");
test.put("content", "梅州城市为背景");
test.put("temperature", "0.5");
// 创建messages数组并将消息对象添加到数组中
JSONArray messagesArray = new JSONArray();
messagesArray.add(messageObject);
messagesArray.add(test);
// 将messages数组添加到最外层的JSON对象中
jsonObject.put("messages", messagesArray);
return jsonObject;
}
控制器
private final static String APIPassword="gQnwqGhbiifKUgtxhQrXnb:JdDduuVNXTxduGIvwtorNjw";
@GetMapping("/chat")
public Flux<String> chat(String text) {
return WebClient.builder()
.defaultHeader("Content-Type", "application/json; charset=UTF-8") // 明确指定UTF-8
.defaultHeader("Authorization","Bearer" + APIPassword)
.baseUrl("https://spark-api-open.xf-yun.com/v2/chat/completions").build()
.post() //post请求
.accept(MediaType.TEXT_EVENT_STREAM)// 设置接受的响应类型
.bodyValue(builderBody("123",text).toString()) //请求体内容
.retrieve() // 执行请求
.bodyToFlux(String.class) // 响应体转换成 String
.map(s->s)
.timeout(Duration.ofSeconds(10)) // 设置请求超时时间,10秒
.retry(3) // 如果发生错误,最多重试3次
.onErrorResume(WebClientRequestException.class, ex ->
Flux.just(ex.getLocalizedMessage())) // 处理 WebClient 请求错误
.doOnTerminate(() -> {
// 终止流时执行的操作,可能用于清理资源等
})
.doOnCancel(() -> {
// 流取消时执行的操作
})
.doFinally(signalType -> {
// 在流结束时执行的操作,包括正常完成、取消或出错等情况
});
}