refactor(服务): 重构多个服务类并添加数据库表初始化方法 style(日志): 优化日志输出格式和内容 docs(任务概览): 更新恶意买家黑名单闭环任务状态 fix(ImageRecognitionService): 修复错误处理中的变量名错误 chore: 移除冗余代码并合并相似功能
76 lines
2.3 KiB
TypeScript
76 lines
2.3 KiB
TypeScript
import { RedisService } from '../../utils/RedisService';
|
|
import { logger } from '../../utils/logger';
|
|
|
|
export type EventCallback = (payload: any) => Promise<void>;
|
|
|
|
/**
|
|
* [BIZ_KER_115] 核心 Domain 间异步解耦建议 (EventBusOptimizationService)
|
|
* @description 核心逻辑:提供高性能的进程内/跨进程事件分发机制。
|
|
* 支持基于 Redis Pub/Sub 的分布式事件同步,以及内存中的快速分发。
|
|
* 用于解耦 Order, Product, Logistics 等核心领域,降低同步调用链深度。
|
|
*/
|
|
export class EventBusOptimizationService {
|
|
private static handlers: Map<string, EventCallback[]> = new Map();
|
|
private static readonly REDIS_EVENT_CHANNEL = 'core:event_bus:broadcast';
|
|
|
|
/**
|
|
* 初始化分布式事件监听
|
|
*/
|
|
static async init() {
|
|
const redis = RedisService.getClient();
|
|
// 订阅 Redis 广播通道
|
|
await RedisService.subscribeToStateSync('EVENT_BUS', async (msg) => {
|
|
if (msg.type === 'BROADCAST_EVENT') {
|
|
await this.emitLocal(msg.event, msg.payload);
|
|
}
|
|
});
|
|
logger.info(`[EventBus] Distributed event bus initialized`);
|
|
}
|
|
|
|
/**
|
|
* 订阅事件
|
|
*/
|
|
static subscribe(event: string, callback: EventCallback) {
|
|
const callbacks = this.handlers.get(event) || [];
|
|
callbacks.push(callback);
|
|
this.handlers.set(event, callbacks);
|
|
logger.info(`[EventBus] Subscribed to event: ${event}`);
|
|
}
|
|
|
|
/**
|
|
* 发布本地事件 (进程内)
|
|
*/
|
|
static async emitLocal(event: string, payload: any) {
|
|
const callbacks = this.handlers.get(event);
|
|
if (callbacks) {
|
|
for (const cb of callbacks) {
|
|
try {
|
|
await cb(payload);
|
|
} catch (err: any) {
|
|
logger.error(`[EventBus] Handler for ${event} failed: ${err.message}`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 发布全局事件 (跨进程/分布式)
|
|
*/
|
|
static async emitGlobal(event: string, payload: any) {
|
|
// 1. 先触发本地监听
|
|
await this.emitLocal(event, payload);
|
|
|
|
// 2. 通过 Redis 广播到其它节点
|
|
try {
|
|
await RedisService.broadcastStateChange('EVENT_BUS', {
|
|
type: 'BROADCAST_EVENT',
|
|
event,
|
|
payload,
|
|
timestamp: Date.now()
|
|
});
|
|
} catch (err: any) {
|
|
logger.error(`[EventBus] Global emit failed: ${err.message}`);
|
|
}
|
|
}
|
|
}
|