在Golang中,将电子邮件发送推迟到队列的最佳且最简单的方法是什么?

huangapple go评论83阅读模式
英文:

Best and simplest way in golang to defer email sending to a queue

问题

我们在Amazon EC2上运行一个简单的Web应用程序,使用Cassandra作为数据库。

如果用户注册的电子邮件可以被延迟/排队处理,甚至可以进行速率限制,那将是很好的。

在不使事情过于复杂的情况下,最符合"Go语言风格"的方式是什么?我知道有很多队列/任务/工作器类似的解决方案,但我更感兴趣的是一种轻量级的解决方案。

英文:

Were running a simple web application on Amazon EC2, cassandra as the database.

It would be good if the user signup email could be deferred/queued, and maybe even rate limited.

What is the most "go like" way to achieve this without making things too complicated? I know there are lots of queue/task/worker like solutions, but I am more interested in something that is lightweight.

答案1

得分: 6

有一个goroutine来处理电子邮件,并使用通道进行通信,例如:

var emailch = make(chan *UserInfo)
//你可以将其设置为带缓冲的通道,这样如果请求过快,它将会阻塞
//var emailch = make(chan *UserInfo, 1000)

func init() {
	go func() {
		for ui := range emailch {
			send_email(ui.Email)
		}
	}()
}

func Register(rw http.ResponseWriter, req *http.Request) {
	//代码
	emailch <- &UserInfo{....}
}

其中emailch是一个通道,用于传递*UserInfo类型的指针。在init()函数中,启动了一个goroutine,它会不断地从emailch通道中接收*UserInfo指针,并调用send_email函数发送电子邮件。在Register函数中,将&UserInfo{....}发送到emailch通道中,以便处理电子邮件。

英文:

Have 1 goroutine to handle the emails and communicate with it using channels, for example :

var emailch = make(chan *UserInfo) 
//you could make it buffered, that way it will block if requests are coming too fast
//var emailch = make(chan *UserInfo, 1000)

func init() {
	go func() {
		for ui := range emailch {
			send_email(ui.Email)
		}
	}()
}

func Register(rw http.ResponseWriter, req *http.Request) {
	//code
	emailch &lt;- &amp;UserInfo{....}
}

答案2

得分: 1

只是为了完整性,我想补充一下,上面的代码并没有创建一个非缓冲通道。注释在某种程度上表明了这一点。

上面的代码make(chan *UserInfo)创建了一个大小为0的缓冲通道。这不是一个非缓冲通道,它会阻塞第一次发送,直到有接收者。

关于缓冲的注释并不是错误的,但有点误导性。

您可以在此页面了解更多关于通道的信息,并进行交互尝试。
https://tour.golang.org/concurrency/2

https://tour.golang.org/concurrency/3

英文:

Just for completion, I would like to add that the above code does not create a unbuffered Channel. The comments indicate this in some way.

> //you could make it buffered, that way it will block if requests are coming too fast
>
> //var emailch = make(chan *UserInfo, 1000)

The above Code make(chan *UserInfo) creates a channel with a buffer of size 0. This is not an unbuffered channel, it will block the first sending until it is Receiver.

The comments regarding buffering are not false, but some kind of misleading.

On this page you can learn more about channels and try interactively.
https://tour.golang.org/concurrency/2

https://tour.golang.org/concurrency/3

huangapple
  • 本文由 发表于 2014年6月9日 11:13:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/24113190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定