以下是一个从零实现类ChatGPT智能聊天机器人的完整开发指南,包含技术选型、核心代码逻辑和推荐学习资源:
—云端平台整理
核心模型
训练框架
部署工具
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("gpt2")
# 对话数据格式处理(OpenAI格式)
def format_data(texts):
return {
"prompt": texts[0],
"completion": texts[1],
"system_message": "你是一个AI助手,回答需简洁专业"
}
# 数据加载与分词
dataset = load_dataset("qingyang/zh_dialogue") # 中文对话数据集
tokenized_data = dataset.map(lambda x: tokenizer(x["text"], truncation=True, max_length=512))
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("gpt2")
# 添加LoRA适配器
lora_config = LoraConfig(
r=8, # 秩
lora_alpha=32,
target_modules=["q_proj", "v_proj"],
lora_dropout=0.05
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters() # 仅训练约0.1%参数
from transformers import pipeline
chatbot = pipeline("text-generation", model=model, tokenizer=tokenizer)
response = chatbot(
"如何学习机器学习?",
max_length=200,
temperature=0.7, # 控制创造性
top_p=0.9, # Nucleus采样
repetition_penalty=1.2
)
print(response[0]['generated_text'])
入门教程
进阶实战
官方参考实现
开源项目
环境准备
conda create -n chatbot python=3.10
pip install torch transformers peft accelerate gradio
训练与部署
# 单卡微调
python train.py --model_name=gpt2 --use_lora=True
# 启动Web服务
python app.py --port=7860 # Gradio界面
通过以上步骤,即可构建一个具备基本对话能力的智能聊天机器人。建议先从API调用(如OpenAI)入手,再逐步深入模型微调和自研架构。
项目描述
在当今高度数字化的世界中,人工智能(AI)的应用越来越广泛,其中,聊天机器人作为一种AI技术,正逐渐成为企业和个人用户的重要工具。ChatGPT,作为OpenAI推出的一款强大的人工智能语言模型,具有强大的自然语言处理能力,可以为用户提供高效、智能的聊天体验。本项目将重点探讨如何基于AI ChatGPT 接口、SpringBoot 和 Vue3,以构建一个功能强大的聊天机器人。项目主要分为前端和后端两部分,前端使用 Vue3 进行页面设计和交互实现,后端使用SpringBoot 搭建服务端,通过调用 AI ChatGPT 接口实现智能聊天功能。
模块 | 技术选型 | 说明 |
---|---|---|
前端 | Vue3 + TypeScript + Pinia | 响应式界面,状态管理 |
后端 | SpringBoot 3.x + JDK 17 | RESTful API + 安全认证 |
AI 集成 | OpenAI API (gpt-3.5-turbo) | 官方SDK调用,上下文对话管理 |
通信协议 | WebSocket + HTTP/HTTPS | 实时对话 + 普通请求 |
数据库 | MySQL 8 + Redis | 存储对话历史、用户数据缓存 |
部署 | Docker + Nginx | 容器化部署,反向代理 |
// 示例:OpenAI 接口调用服务
@Service
public class ChatService {
private final OpenAiService openAiService; // 官方Java SDK封装
public ChatResponse generateResponse(ChatRequest request) {
// 构建对话上下文(保留最近5轮对话)
List<Message> messages = request.getMessages()
.stream()
.limit(5)
.map(msg -> new Message(msg.getRole(), msg.getContent()))
.collect(Collectors.toList());
// 调用ChatGPT API
CompletionResult result = openAiService.createChatCompletion(
CompletionRequest.builder()
.model("gpt-3.5-turbo")
.messages(messages)
.temperature(0.7)
.build()
);
return new ChatResponse(result.getChoices().get(0).getMessage().getContent());
}
}
{{ msg.content }}
// 示例:敏感词过滤拦截
public boolean containsSensitiveWords(String text) {
SensitiveFilter filter = new SensitiveFilter();
return filter.contains(text);
}
-- 对话记录表
CREATE TABLE chat_history (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
session_id VARCHAR(64) NOT NULL, -- 会话ID
user_message TEXT NOT NULL,
ai_response TEXT NOT NULL,
create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
-- 用户表(如需登录功能)
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE,
password_hash VARCHAR(100)
);
本地开发环境
# 后端启动
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
# 前端启动
npm run dev
生产环境部署
# SpringBoot Dockerfile示例
FROM openjdk:17-jdk-slim
COPY target/chatbot-api.jar /app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
压力测试
使用JMeter模拟100并发用户,验证API响应时间(目标:<2s/请求)
API密钥泄露防护
长文本处理
tiktoken
库计算Token数量,避免超过模型限制(4096 tokens)错误处理优化
@ExceptionHandler(OpenAiHttpException.class)
public ResponseEntity<ErrorResponse> handleOpenAiError(OpenAiHttpException ex) {
return ResponseEntity.status(ex.statusCode)
.body(new ErrorResponse("AI服务繁忙,请稍后重试"));
}
通过以上方案,可在4-6周内完成一个具备基础对话能力的全栈智能聊天系统,后续可逐步迭代扩展功能。
应用场景
客户服务:为客户提供实时的问题解答、订单查询、投诉处理等服务。
在线销售:提供产品推荐、购物指导、优惠信息等服务。
医疗健康:为用户提供疾病诊断、治疗方案、药品推荐等服务。
教育领域:学习辅助工具,提供课程咨询、作业辅导、知识问答等服务。
金融理财:为用户提供投资建议、风险评估、市场分析等服务。
社交媒体:为用户提供好友推荐、动态推送、话题讨论等服务
针对不同应用场景的特性,采用模块化插件设计,基于统一AI核心扩展场景专属功能:
// 订单查询服务(SpringBoot示例)
@Service
public class OrderService {
@Autowired
private CRMClient crmClient;
public String queryOrder(String userId, String orderId) {
// 对接企业CRM系统
Order order = crmClient.getOrder(orderId);
return String.format("订单状态:%s,预计送达时间:%s",
order.getStatus(), order.getDeliveryTime());
}
}
{{ item.name }} ¥{{ item.price }}
# 医疗问答验证服务(Python中间件)
def validate_medical_response(response):
# 对接权威医学知识库
with MedicalGraph() as graph:
verified = graph.check_symptom_match(response)
return verified ? response : "建议咨询专业医师"
// 作业批改服务(SpringBoot)
@Service
public class HomeworkService {
public CorrectionResult correctHomework(File homeworkFile) {
// 集成OCR识别+公式解析
String content = MathOCR.parse(homeworkFile);
return ChatGPTClient.requestCorrection(content);
}
}
# 风险评估模型(Python服务)
def assess_risk(user_profile):
model = load_model('risk_assessment.pkl')
return model.predict([
user_profile['age'],
user_profile['income'],
user_profile['investment_exp']
])
// 动态推荐算法(Vue3组合式API)
export function useSocialRecommend() {
const generateRecommendations = async (userId) => {
const graph = await SocialGraphService.getUserGraph(userId);
return graph.nodes
.filter(node => node.weight > 0.8)
.sort((a,b) => b.lastInteraction - a.lastInteraction);
}
return { generateRecommendations }
}
// 场景分类服务
public class SceneRouter {
public String detectScene(String query) {
String[] keywords = {
"订单号", // 客户服务
"推荐", // 在线销售
"头疼", // 医疗健康
"作业", // 教育辅助
"股票", // 金融理财
"好友" // 社交媒体
};
// 使用AC自动机实现高效匹配
AhoCorasick trie = new AhoCorasick(keywords);
return trie.match(query);
}
}
-- 跨场景会话记录表
CREATE TABLE conversation (
session_id VARCHAR(64) PRIMARY KEY,
user_id INT,
current_scene VARCHAR(20),
context JSON, -- 存储场景相关上下文
created_at TIMESTAMP
);
安全层级 | 实现措施 |
---|---|
数据传输 | HTTPS + WSS (WebSocket Secure) |
敏感信息 | AES-256加密存储 |
API防护 | 签名验证 + 请求频率限制 |
内容审核 | 三级过滤(关键词→AI识别→人工复审) |
跨场景上下文继承
// 场景切换时保留有效信息
public void handleSceneSwitch(String newScene, ConversationContext context) {
if (currentScene.equals("医疗健康") && newScene.equals("在线销售")) {
context.remove("symptoms"); // 清除医疗敏感信息
context.keep("user_preferences");
}
}
长对话性能优化
# 对话历史压缩算法
def compress_history(history):
summarized = []
for i in range(0, len(history), 3):
batch = history[i:i+3]
summary = ChatGPT.summarize("\n".join(batch))
summarized.append(summary)
return summarized
多模态内容处理
第一阶段(1-2周)
第二阶段(3-4周)
第三阶段(5-6周)
第四阶段(7-8周)
通过此方案,可在8周内构建支持多场景的智能聊天系统,各模块既可独立运行,也可通过场景路由协同工作。建议采用渐进式交付策略,优先落地高价值场景(如客户服务),逐步扩展至其他领域。
技术选型
SpringBoot
Server-Sent Events 或 WebSocket
Vue3
ChatGPT API
技术项 | 选项1 | 选项2 | 最终选择 | 选择依据 |
---|---|---|---|---|
通信协议 | WebSocket | Server-Sent Events | WebSocket | 支持全双工通信,适合需要双向实时交互的聊天场景 |
前端框架 | React | Vue2 | Vue3 | 组合式API更适合复杂交互,性能优化更好,TypeScript支持更完善 |
状态管理 | Vuex | Pinia | Pinia | 专为Vue3设计,更轻量且支持TypeScript |
后端安全认证 | JWT | OAuth2 | JWT+OAuth2 | JWT用于服务间认证,OAuth2用于第三方登录集成 |
AI服务部署 | 直接调用OpenAI API | 代理服务中转 | 代理服务中转 | 避免前端暴露API密钥,增强请求控制和日志审计 |
// WebSocket配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatHandler(), "/chat")
.setAllowedOrigins("*")
.addInterceptors(new AuthInterceptor());
}
@Bean
public WebSocketHandler chatHandler() {
return new TextWebSocketHandler() {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
// 处理消息并调用ChatGPT服务
String response = chatService.process(message.getPayload());
session.sendMessage(new TextMessage(response));
}
};
}
}
// websocket.service.ts
class ChatSocket {
private socket: WebSocket | null = null;
private messageQueue: string[] = [];
connect(token: string) {
this.socket = new WebSocket(`wss://api.example.com/chat?token=${token}`);
this.socket.onmessage = (event) => {
store.dispatch('receiveMessage', JSON.parse(event.data));
};
this.socket.onopen = () => {
this.messageQueue.forEach(msg => this.send(msg));
this.messageQueue = [];
};
}
send(message: string) {
if (this.socket?.readyState === WebSocket.OPEN) {
this.socket.send(message);
} else {
this.messageQueue.push(message);
}
}
}
// 带熔断机制的API调用
@Service
public class AIService {
private final CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("gpt");
public String callGPT(String prompt) {
return circuitBreaker.executeSupplier(() -> {
OpenAiService service = new OpenAiService(apiKey, Duration.ofSeconds(30));
CompletionRequest request = CompletionRequest.builder()
.model("gpt-3.5-turbo")
.messages(List.of(new ChatMessage("user", prompt)))
.temperature(0.7)
.build();
return service.createChatCompletion(request)
.getChoices().get(0).getMessage().getContent();
});
}
}
通信层优化
# Nginx WebSocket配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
location /chat {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 3600s;
}
}
缓存策略
// 高频问答缓存(Spring Cache + Redis)
@Cacheable(value = "commonQuestions", key = "#question.hashCode()")
public String getCachedResponse(String question) {
return aiService.callGPT(question);
}
批处理优化
# 异步批量处理请求(Python辅助服务)
async def batch_process(prompts: List[str]):
async with OpenAIAsyncClient() as client:
responses = await asyncio.gather(
*[client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": p}]
) for p in prompts]
)
return [r.choices[0].message.content for r in responses]
安全威胁 | 防护措施 |
---|---|
API密钥泄露 | 密钥存储在Vault中,通过Spring Cloud Config动态获取 |
DDoS攻击 | Cloudflare防护 + Nginx限流配置(limit_req_zone) |
注入攻击 | 输入内容双重过滤(前端XSS过滤 + 服务端正则校验) |
会话劫持 | WebSocket连接使用wss协议 + JWT签名验证 |
敏感数据泄露 | 对话记录AES-256加密存储,传输过程使用TLS 1.3 |
插件化架构
// 插件接口定义
public interface ChatPlugin {
boolean supports(String input);
String process(String input, Context context);
}
// 示例:计算器插件
@Component
public class CalculatorPlugin implements ChatPlugin {
@Override
public boolean supports(String input) {
return input.matches(".*\\d+[+\\-*/]\\d+.*");
}
@Override
public String process(String input, Context context) {
// 解析并执行数学计算
return eval(input).toString();
}
}
横向扩展方案
# Kubernetes部署配置
apiVersion: apps/v1
kind: Deployment
spec:
replicas: 3
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
spec:
containers:
- name: chat-service
image: chat-service:1.0
ports:
- containerPort: 8080
envFrom:
- secretRef:
name: openai-secret
监控体系
CI/CD流水线
// Jenkins Pipeline示例
pipeline {
agent any
stages {
stage('Build') {
steps {
sh './mvnw clean package -DskipTests'
}
}
stage('Test') {
steps {
sh './mvnw test'
sh 'npm run test:ci'
}
}
stage('Deploy') {
when {
branch 'main'
}
steps {
sh 'docker build -t chat-service .'
sh 'kubectl apply -f k8s/'
}
}
}
}
通过以上技术选型与实施方案,可构建一个具备高可用性、强安全性和优秀扩展性的智能聊天系统。建议采用渐进式开发策略,优先实现核心聊天功能,再逐步扩展插件和优化性能。
功能点
基本对话交互
用户输入文本,AI能够实时回复
支持多轮对话,维持上下文的连贯性
打造出专业级ChatGPT 风格聊天界面
后台管理端
使用Spring MVC或Spring WebFlux等技术实现API的调用。在控制器中,编写相应的HTTP请求方法,将用户的输入发送给ChatGPT,并接收其返回的响应。根据ChatGPT的响应格式,解析返回的数据,并根据需求展示给用户或执行相应的操作
// WebSocket处理类(WebFlux)
@Component
public class ChatHandler implements WebSocketHandler {
@Autowired
private ChatGPTService chatService;
@Override
public Mono<Void> handle(WebSocketSession session) {
return session.receive()
.map(webSocketMessage -> {
ChatMessage message = parseMessage(webSocketMessage.getPayloadAsText());
return chatService.generateResponse(message);
})
.flatMap(response ->
session.send(Mono.just(session.textMessage(response)))
);
}
}
// 对话上下文对象
public class ConversationContext {
private String sessionId;
private List<ChatMessage> history = new ArrayList<>();
private LocalDateTime expireTime;
public void addMessage(ChatMessage message) {
if (history.size() >= 10) { // 保留最近10条
history.remove(0);
}
history.add(message);
}
}
# application.yml
spring:
redis:
host: redis-cluster.prod
port: 6379
timeout: 3000
conversation:
ttl: 30m # 会话30分钟无活动失效
public String buildPrompt(ConversationContext context) {
StringBuilder prompt = new StringBuilder("当前对话上下文:\n");
context.getHistory().forEach(msg ->
prompt.append(msg.getRole())
.append(": ")
.append(msg.getContent())
.append("\n")
);
prompt.append("请根据以上对话继续回复:");
return prompt.toString();
}
// 打字机效果实现
const displayResponse = (response: string) => {
let index = 0;
const tempMsg = { content: '', sender: 'ai' };
messages.value.push(tempMsg);
const timer = setInterval(() => {
if (index < response.length) {
tempMsg.content += response.charAt(index);
index++;
// 自动滚动到底部
nextTick(() => scrollToBottom());
} else {
clearInterval(timer);
}
}, 30);
};
// ChatGPT风格样式
.chat-container {
max-width: 800px;
margin: 0 auto;
background: linear-gradient(180deg, #f5f7fa 0%, #e6e9ef 100%);
.message.ai .bubble {
background: #ffffff;
border-radius: 18px 18px 18px 4px;
box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
.message.user .bubble {
background: #007bff;
color: white;
border-radius: 18px 18px 4px 18px;
}
}
模块 | 功能点 |
---|---|
会话监控 | 实时查看在线会话、强制断开连接 |
数据分析 | 对话量统计、热词分析、用户活跃度报表 |
敏感词管理 | 动态更新过滤词库、查看命中记录 |
API监控 | ChatGPT调用统计、响应时间监控、错误日志 |
// 会话管理接口
@RestController
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {
@GetMapping("/active-sessions")
public List<WebSocketSession> getActiveSessions() {
return sessionRegistry.getAllSessions();
}
@PostMapping("/disconnect/{sessionId}")
public void forceDisconnect(@PathVariable String sessionId) {
sessionRegistry.getSession(sessionId).close();
}
}
// 异步消息处理
@Async("chatThreadPool")
public CompletableFuture<String> processMessageAsync(ChatMessage message) {
return CompletableFuture.supplyAsync(() -> {
return chatService.generateResponse(message);
});
}
// 线程池配置
@Bean("chatThreadPool")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(100);
return executor;
}
// 高频问答缓存
@Cacheable(value = "commonResponses", key = "#message.hashCode()")
public String getCachedResponse(ChatMessage message) {
return chatService.generateResponse(message);
}
// Redis缓存配置
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.builder(factory)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5))
.disableCachingNullValues())
.build();
}
}
安全层级 | 实现措施 |
---|---|
传输安全 | WSS协议 + TLS 1.3加密 |
身份认证 | JWT令牌验证 + OAuth2.0第三方登录 |
输入过滤 | 三级过滤(前端过滤 → 服务端正则校验 → AI内容安全接口) |
API防护 | 请求签名 + 速率限制(Guava RateLimiter) |
审计追踪 | 全链路日志追踪 + 敏感操作二次验证 |
// WebSocket握手拦截器
public class AuthHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Map<String, Object> attributes) {
String token = request.getHeaders().getFirst("Sec-WebSocket-Protocol");
return jwtService.validateToken(token);
}
}
V1.0基础版(2周)
V1.1体验优化(1周)
V2.0扩展版(3周)
本方案通过前后端分离架构实现高内聚低耦合,采用WebSocket保证实时性,结合Redis维护对话上下文,利用Spring Security保障系统安全。建议采用敏捷开发模式,分阶段交付核心功能,持续收集用户反馈进行迭代优化。
项目实现参考
使用SpringBoot作为主要的后端框架,负责处理业务逻辑和数据交互。
集成WebSocket或SSE,用于实现实时通信,让用户能够与聊天机器人进行即时对话。
对接ChatGPT接口,通过HTTP请求与GPT-3.5或GPT-4.0模型进行交互,处理用户的输入并生成回复。
2. 前端实现:
采用Vue3作为前端框架,利用其响应式和组件化的特性来构建用户界面。
使用Vite4作为前端开发服务器,它提供了更快的冷启动和更新速度。
利用Vue Router进行路由管理,确保前端页面之间的合理跳转和组织。
实现动态打字机效果,增强用户体验,使对话看起来像是实时发生的。
3. 用户体验优化:
设计清晰直观的用户界面,让用户轻松与聊天机器人进行交互。
优化聊天机器人的回复速度和准确性,确保用户获得满意的回答。
// WebSocket安全配置
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private JwtAuthInterceptor jwtInterceptor;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatWebSocketHandler(), "/ws/chat")
.setAllowedOrigins("*")
.addInterceptors(jwtInterceptor)
.withSockJS();
}
@Bean
public WebSocketHandler chatWebSocketHandler() {
return new ChatMessageHandler();
}
}
// JWT握手拦截器
@Component
public class JwtAuthInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Map<String, Object> attributes) {
String token = extractToken(request);
return JwtUtil.validateToken(token);
}
private String extractToken(ServerHttpRequest request) {
// 从Header或Query参数获取Token
List<String> headers = request.getHeaders().get("Sec-WebSocket-Protocol");
return headers != null ? headers.get(0) : "";
}
}
@Service
public class ChatGPTService {
@Value("${openai.api.key}")
private String apiKey;
@Autowired
private RedisTemplate<String, Conversation> redisTemplate;
public String processMessage(String sessionId, String input) {
// 获取或创建会话上下文
Conversation conversation = redisTemplate.opsForValue().get(sessionId);
if (conversation == null) {
conversation = new Conversation(sessionId);
}
// 维护对话历史(保留最近5轮)
conversation.addMessage(new ChatMessage("user", input));
if (conversation.getMessages().size() > 10) {
conversation.getMessages().remove(0);
}
// 组装带上下文的Prompt
String prompt = buildPromptWithHistory(conversation.getMessages());
// 调用ChatGPT API
OpenAiService service = new OpenAiService(apiKey, Duration.ofSeconds(30));
CompletionRequest request = CompletionRequest.builder()
.model("gpt-3.5-turbo")
.messages(conversation.getMessages())
.maxTokens(500)
.build();
String response = service.createChatCompletion(request)
.getChoices().get(0).getMessage().getContent();
// 更新上下文并存储
conversation.addMessage(new ChatMessage("assistant", response));
redisTemplate.opsForValue().set(sessionId, conversation, Duration.ofHours(2));
return response;
}
}
@Configuration
public class CircuitBreakerConfig {
@Bean
public CircuitBreakerRegistry circuitBreakerRegistry() {
return CircuitBreakerRegistry.of(
CircuitBreakerConfig.custom()
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofSeconds(30))
.slidingWindowSize(10)
.build()
);
}
@Bean
@Qualifier("chatGPTCircuitBreaker")
public CircuitBreaker chatGPTCircuitBreaker() {
return circuitBreakerRegistry().circuitBreaker("chatGPT");
}
}
// src/utils/websocket.ts
import { ref, onUnmounted } from 'vue'
export class ChatSocket {
private socket: WebSocket | null = null
private messageQueue: string[] = []
private retries = 0
private maxRetries = 3
constructor(private url: string, private token: string) {}
connect() {
this.socket = new WebSocket(`${this.url}?token=${this.token}`)
this.socket.onopen = () => {
this.retries = 0
this.flushQueue()
}
this.socket.onmessage = (event) => {
this.handleMessage(event.data)
}
this.socket.onclose = (event) => {
if (event.wasClean || this.retries >= this.maxRetries) return
setTimeout(() => this.reconnect(), Math.min(2000 * this.retries, 10000))
}
}
private reconnect() {
this.retries++
this.connect()
}
private flushQueue() {
while (this.messageQueue.length > 0) {
this.send(this.messageQueue.shift()!)
}
}
send(message: string) {
if (this.socket?.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(message))
} else {
this.messageQueue.push(message)
}
}
}
// 使用示例
export function useChatSocket() {
const socket = ref<ChatSocket>()
const init = (token: string) => {
socket.value = new ChatSocket('wss://your-api.com/ws/chat', token)
socket.value.connect()
}
onUnmounted(() => {
socket.value?.disconnect()
})
return { socket, init }
}
# Nginx配置优化
http {
# WebSocket代理配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
}
}
# 前端静态资源缓存
location /assets/ {
expires 1y;
add_header Cache-Control "public";
}
}
// 智能重试机制
const fetchWithRetry = async (url: string, options: RequestInit, retries = 3) => {
try {
const response = await fetch(url, options)
if (!response.ok) throw new Error(response.statusText)
return response.json()
} catch (error) {
if (retries > 0) {
await new Promise(resolve => setTimeout(resolve, 1000))
return fetchWithRetry(url, options, retries - 1)
}
throw error
}
}
⚠️ 出现意外错误
{{ error.message }}
# SpringBoot Dockerfile
FROM eclipse-temurin:17-jdk-alpine
VOLUME /tmp
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
# Vue前端Dockerfile
FROM node:16-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Prometheus配置
scrape_configs:
- job_name: 'springboot'
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['app:8080']
- job_name: 'node'
static_configs:
- targets: ['frontend:9100']
智能功能增强
多模态支持
// 图片处理示例
public String analyzeImage(String imageUrl) {
ChatMessage imageMessage = new ChatMessage("user");
imageMessage.setContent(List.of(
new ContentItem("text", "请描述这张图片"),
new ContentItem("image_url", imageUrl)
));
return chatService.processMessage(sessionId, imageMessage);
}
企业级特性
通过以上实现方案,您可以快速搭建一个高可用、实时交互的智能聊天系统。建议在开发过程中: