dousong2023 2018-04-16 04:51
浏览 24
已采纳

api视图中的golang后台工作者进程

We are planning to move to golang from django.

To send an email or sms, we do celery workers with redis/rabbotmq in Django. But how can we do that background tasks on golang.

Eg:

def api_view():

 // logic

 // celery tasks- call email/sms service

 // immediate response to client
 return Response()

How can we do in golang

fun ApiView(w http.ResponseWriter, req *http.Request){

 //logic

 // need to call email/sms service


 fmt.Fprintf(w, "TEST")
}

Is there anything we can start new go routine (without additional redis/workers) inside the API view of gorilla/mux ?

Thanks.

  • 写回答

1条回答 默认 最新

  • dongsilu2237 2018-04-16 11:51
    关注

    Yes! As comments stated you can spawn a new go routine within the context of your view. The goroutine gets its own stack and allows it to operate "asynchronously" from the view handling function:

    func ApiView(w http.ResponseWriter, req *http.Request){
    
     //logic
    
     // need to call email/sms service
     go sendEmail(someEmailAddress)
    
     fmt.Fprintf(w, "TEST")
    }
    

    This will execute sendEmail using a go routine and immediately write TEST to the caller.


    While trivial it is not equivalent to celery redis/rabbitmq:

    • How do you handle failures?
    • How do you bound concurrency (worker pool)
    • How do you buffer tasks? (ie currently in rabbitmq it is out of process)
    • How do you retry?
    • Should the async task be in a different process/memory space?

    None of the above are particularly difficult, and completely doable (and plenty of patterns/blogs/libraries exist for doing this exact thing)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)