Request 同步请求(等待响应)
(target *PID, msg Message, timeout time.Duration)
| 293 | |
| 294 | // Request 同步请求(等待响应) |
| 295 | func (s *System) Request(target *PID, msg Message, timeout time.Duration) (Message, error) { |
| 296 | if !s.isRunning.Load() { |
| 297 | return nil, errors.New("actor system is not running") |
| 298 | } |
| 299 | |
| 300 | // 使用 context 来取消请求 |
| 301 | ctx, cancel := context.WithTimeout(context.Background(), timeout) |
| 302 | defer cancel() |
| 303 | |
| 304 | responseChan := make(chan Message, 1) |
| 305 | env := envelope{ |
| 306 | target: target, |
| 307 | sender: nil, |
| 308 | message: msg, |
| 309 | sentAt: time.Now(), |
| 310 | response: responseChan, |
| 311 | ctx: ctx, |
| 312 | } |
| 313 | |
| 314 | select { |
| 315 | case s.mailbox <- env: |
| 316 | atomic.AddInt64(&s.stats.TotalMessages, 1) |
| 317 | case <-ctx.Done(): |
| 318 | return nil, &ResponseTimeout{Target: target, Timeout: timeout} |
| 319 | } |
| 320 | |
| 321 | select { |
| 322 | case resp := <-responseChan: |
| 323 | return resp, nil |
| 324 | case <-ctx.Done(): |
| 325 | return nil, &ResponseTimeout{Target: target, Timeout: timeout} |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // Stop 停止 Actor |
| 330 | func (s *System) Stop(pid *PID) { |