Files
rongtongjin/test-concurrent-fetch.ts
T

91 lines
2.8 KiB
TypeScript
Raw Normal View History

import { DatabaseService } from './src/services/database.js';
import { ScraperService } from './src/services/scraper.js';
import { SilverBaselineMonitor } from './src/services/silver-baseline-monitor.js';
import { AlertService } from './src/utils/alert.js';
import 'dotenv/config';
/**
* 测试并发获取价格(模拟实际运行场景)
*/
async function testConcurrentFetch(): Promise<void> {
console.log('========================================');
console.log('测试并发价格获取');
console.log('========================================\n');
const db = new DatabaseService();
const scraper = new ScraperService();
const alertService = new AlertService();
try {
// 初始化
console.log('1. 初始化服务...');
await db.init();
await alertService.init();
await scraper.init();
console.log('✅ 初始化完成\n');
// 创建监控服务
const threshold = Number(process.env.SILVER_BASELINE_THRESHOLD) || 0.2;
const monitor = new SilverBaselineMonitor(
db,
threshold,
alertService,
process.env.WEBHOOK_URL
);
// 模拟并发获取(就像实际运行时一样)
console.log('2. 并发获取价格(模拟实际场景)...');
const results = await Promise.allSettled([
scraper.fetchSilverPrices(),
scraper.fetchSilverPrice()
]);
console.log('\n结果:');
results.forEach((result, index) => {
const name = index === 0 ? '价差监控' : '白银基线监控';
if (result.status === 'fulfilled') {
console.log(`✅ ${name}: 成功`);
if (result.value) {
if (index === 0) {
const data = result.value as any;
console.log(` 美白银: ${data.usSilver}, 伦敦银: ${data.londonSilver}`);
} else {
const data = result.value as any;
console.log(` 白银销售价: ${data.sellPrice}`);
}
}
} else {
console.log(`❌ ${name}: 失败 - ${result.reason}`);
}
});
console.log('\n3. 再次测试(确保可以重复执行)...');
const results2 = await Promise.allSettled([
scraper.fetchSilverPrices(),
scraper.fetchSilverPrice()
]);
console.log('\n第二次结果:');
results2.forEach((result, index) => {
const name = index === 0 ? '价差监控' : '白银基线监控';
if (result.status === 'fulfilled') {
console.log(`✅ ${name}: 成功`);
} else {
console.log(`❌ ${name}: 失败 - ${result.reason}`);
}
});
console.log('\n========================================');
console.log('测试完成!');
console.log('========================================');
} catch (error) {
console.error('测试失败:', error);
} finally {
await scraper.close();
}
}
// 运行测试
testConcurrentFetch();