* 注册请求处理器(用于请求-响应模式) * * @param topic - 请求主题 * @param handler - 请求处理器,可以返回响应数据 * @returns 取消注册的函数
(
topic: string,
handler: RequestHandler<TRequest, TResponse>
)
| 229 | * @returns 取消注册的函数 |
| 230 | */ |
| 231 | public onRequest<TRequest = any, TResponse = any>( |
| 232 | topic: string, |
| 233 | handler: RequestHandler<TRequest, TResponse> |
| 234 | ): () => void { |
| 235 | if (this.requestHandlers.has(topic)) { |
| 236 | logger.warn(`Request handler for topic "${topic}" already exists, replacing...`); |
| 237 | } |
| 238 | |
| 239 | const subscription: RequestSubscription = { |
| 240 | topic, |
| 241 | handler |
| 242 | }; |
| 243 | |
| 244 | this.requestHandlers.set(topic, subscription); |
| 245 | logger.debug(`Registered request handler for topic: ${topic}`); |
| 246 | |
| 247 | return () => { |
| 248 | if (this.requestHandlers.get(topic) === subscription) { |
| 249 | this.requestHandlers.delete(topic); |
| 250 | logger.debug(`Unregistered request handler for topic: ${topic}`); |
| 251 | } |
| 252 | }; |
| 253 | } |
| 254 | |
| 255 | /** |
| 256 | * 发送请求并等待响应(请求-响应模式) |