我有一個為請求提供服務的終結點。在請求流中,終結點需要生成并發送電子郵件通知(讓我們命名代碼)。我希望端點異步調用 。端點不應等待 。sendEmail()sendEmail()sendEmail()代碼是這樣的:func (s *server) MyEndpoint(ctx context.Context, request *MyRequest) (MyResponse, error) { // other logic // async sendEmail() // end async // other logic - should not wait for the response from sendEmail return getMyResponse(), nil}我該怎么做?我意識到這可能是基本的,但我是Go的新手,并希望確保我遵循最佳實踐。
1 回答

MYYA
TA貢獻1868條經驗 獲得超4個贊
使用 go 例程可以
執行并發代碼。在您的示例中,您希望在返回時獲取響應。執行此操作的一種方法是使用通道。
您可以通過將一個通道傳遞給兩個函數來做到這一點,其中一個生成數據,另一個函數使用數據。這里有一篇關于頻道的很棒的文章。它看起來像這樣(注意我在這里使用了interface{}類型,如果你得到了一個具體的類型,它是更可取的方式)
func (s *server) MyEndpoint(ctx context.Context, request *MyRequest) (MyResponse, error) {
// other logic
// async
c := make(chan interface{})
go sendEmail(c)
// end async
// other logic - should not wait for the response from sendEmail
// getMyResponse must happen only after sendEmail has done
return getMyResponse(c), nil
}
- 1 回答
- 0 關注
- 109 瀏覽
添加回答
舉報
0/150
提交
取消