新功能: - 创建AI聊天助手组件(AIChatWidget) - 支持文字+图片多模态对话 - 集成Gemini AI API - 支持图片编辑和内容生成 - 实时对话历史管理 - 优雅的UI设计,支持黑夜模式 技术实现: - 后端API代理Gemini API(/api/ai-chat) - 支持最多5张图片上传 - 流式响应处理 - 对话历史管理 - Base64图片处理 配置: - 在.env中添加Gemini API配置 - GEMINI_API_KEY - GEMINI_API_BASE_URL - GEMINI_MODEL 替换原弹幕功能,提供更强大的AI助手体验!
78 lines
2.4 KiB
JavaScript
Executable File
78 lines
2.4 KiB
JavaScript
Executable File
const mongoose = require('mongoose');
|
||
const dotenv = require('dotenv');
|
||
|
||
dotenv.config();
|
||
|
||
// 数据库连接URL
|
||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/aigc-platform';
|
||
|
||
// 连接选项
|
||
const options = {
|
||
serverSelectionTimeoutMS: 10000, // 减少服务器选择超时时间
|
||
socketTimeoutMS: 30000, // 减少套接字超时时间
|
||
connectTimeoutMS: 10000, // 减少连接超时时间
|
||
retryWrites: true,
|
||
maxPoolSize: 10, // 连接池大小
|
||
};
|
||
|
||
// 连接数据库
|
||
const connectDB = async (retryCount = 0, maxRetries = 2) => {
|
||
try {
|
||
console.log('尝试连接数据库...');
|
||
|
||
// 设置一个超时,如果连接时间过长就中断
|
||
const timeoutPromise = new Promise((_, reject) => {
|
||
setTimeout(() => {
|
||
reject(new Error('数据库连接超时,中断连接尝试'));
|
||
}, 15000); // 15秒超时
|
||
});
|
||
|
||
// 尝试连接数据库
|
||
const connectionPromise = mongoose.connect(MONGODB_URI, options);
|
||
|
||
// 使用Promise.race来实现超时控制
|
||
const conn = await Promise.race([connectionPromise, timeoutPromise]);
|
||
|
||
console.log(`MongoDB 连接成功: ${conn.connection.host}`);
|
||
return conn;
|
||
} catch (error) {
|
||
console.error(`MongoDB 连接错误: ${error.message}`);
|
||
|
||
// 如果还有重试次数,则尝试重新连接
|
||
if (retryCount < maxRetries) {
|
||
console.log(`尝试重新连接数据库 (${retryCount + 1}/${maxRetries})...`);
|
||
// 等待一段时间后重试
|
||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||
return connectDB(retryCount + 1, maxRetries);
|
||
}
|
||
|
||
console.error('数据库连接失败: ' + error.message);
|
||
console.warn('应用将在没有数据库连接的情况下启动。用户认证和其他需要数据库的功能将不可用。');
|
||
// 不抛出错误,而是返回null表示连接失败
|
||
return null;
|
||
}
|
||
};
|
||
|
||
// 监听连接事件
|
||
mongoose.connection.on('connected', () => {
|
||
console.log('MongoDB连接已建立');
|
||
});
|
||
|
||
mongoose.connection.on('error', (err) => {
|
||
console.error('MongoDB连接错误:', err.message);
|
||
});
|
||
|
||
mongoose.connection.on('disconnected', () => {
|
||
console.warn('MongoDB连接已断开');
|
||
});
|
||
|
||
// 应用关闭时关闭数据库连接
|
||
process.on('SIGINT', async () => {
|
||
if (mongoose.connection.readyState !== 0) {
|
||
await mongoose.connection.close();
|
||
console.log('MongoDB连接已关闭(应用终止)');
|
||
}
|
||
process.exit(0);
|
||
});
|
||
|
||
module.exports = { connectDB, mongoose }; |