英文:
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 <- &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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论