要在Java项目中调用Dify接口,并将流式对话消息传递给前端(Vue项目),你可以使用Spring Boot作为后端框架,并通过WebSocket或Server-Sent Events (SSE) 实现流式传输。以下是一个简单的示例,展示如何在Java后端调用Dify接口,并将流式响应传递给Vue前端。
1. Java后端(Spring Boot)
1.1 添加依赖
首先,在pom.xml中添加必要的依赖:
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-websocket
com.squareup.okhttp3
okhttp
4.9.3
1.2 创建WebSocket配置
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ChatWebSocketHandler(), "/chat").setAllowedOrigins("*");
}
}
1.3 创建WebSocket处理器
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
public class ChatWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String userMessage = message.getPayload();
// Call Dify API and stream the response
streamDifyResponse(userMessage, session);
}
private void streamDifyResponse(String userMessage, WebSocketSession session) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.dify.ai/v1/chat") // Dify API endpoint
.post(RequestBody.create(userMessage, MediaType.parse("application/json")))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try (ResponseBody responseBody = response.body()) {
if (responseBody != null) {
BufferedReader reader = new BufferedReader(responseBody.charStream());
String line;
while ((line = reader.readLine()) != null) {
session.sendMessage(new TextMessage(line));
}
}
}
}
}
});
}
}
1.4 启动Spring Boot应用
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DifyChatApplication {
public static void main(String[] args) {
SpringApplication.run(DifyChatApplication.class, args);
}
}
2. Vue前端
2.1 安装WebSocket库
npm install vue-native-websocket
2.2 在Vue组件中使用WebSocket
{{ msg }}
<script>
import VueNativeSock from 'vue-native-websocket'
export default {
data() {
return {
message: '',
messages: []
}
},
created() {
VueNativeSock('ws://localhost:8080/chat', {
format: 'json',
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 3000,
})
},
sockets: {
connect() {
console.log('WebSocket connected')
},
message(data) {
this.messages.push(data)
}
},
methods: {
sendMessage() {
this.$socket.send(this.message)
this.message = ''
}
}
}
</script>
3. 运行项目
- 启动Spring Boot应用。
- 启动Vue前端项目。
- 在Vue前端输入消息,消息将通过WebSocket发送到Java后端,Java后端调用Dify API并将流式响应返回给前端。
总结
这个示例展示了如何使用Spring Boot和Vue实现一个简单的流式聊天应用。Java后端通过WebSocket与前端通信,并调用Dify API获取流式响应。前端通过WebSocket接收并显示流式消息。你可以根据实际需求进一步扩展和优化这个示例。