亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何異步發送電子郵件?

如何異步發送電子郵件?

Go
胡子哥哥 2022-08-30 21:40:27
我有一個為請求提供服務的終結點。在請求流中,終結點需要生成并發送電子郵件通知(讓我們命名代碼)。我希望端點異步調用 。端點不應等待 。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

}


查看完整回答
反對 回復 2022-08-30
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號