5

Golang 中使用「Event - Listener」解耦逻辑,让你的应用更简单!

 2 years ago
source link: https://studygolang.com/articles/35837
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Golang 中使用「Event - Listener」解耦逻辑,让你的应用更简单!

hwbrzzl · 大约22小时之前 · 266 次点击 · 预计阅读时间 2 分钟 · 大约8小时之前 开始浏览    

当一个订单完成时,老板说:发个短信给用户,再发个邮件吧,同时更新下统计数据,巴拉巴拉(真事多)。

我们当然可以用 goroutine 处理这些耗时的任务,但优雅的一种方式是使用「事件系统(Event - Listener 模式)」来进行代码的解耦,让代码逻辑更简单!

跟 Laravel 的使用方法完全一致,Phper 请安心服用。

第一步:生成任务类

go run . artisan make:event PodcastProcessed
go run . artisan make:listener SendPodcastNotification

第二步:注册事件和监听器

package providers

import (
  "github.com/goravel/framework/contracts/events"
  "github.com/goravel/framework/support/facades"
)

type EventServiceProvider struct {
}

...

func (receiver *EventServiceProvider) listen() map[events.Event][]events.Listener {
  return map[events.Event][]events.Listener{
    &events.OrderShipped{}: {
      &listeners.SendShipmentNotification{},
    },
  }
}

第三步:实现 Listener 逻辑

第四步:调度事件

err := facades.Event.Job(&events.OrderShipped{}, []events.Arg{
    {Type: "string", Value: "abcc"},
    {Type: "int", Value: 1234},
  }).Dispatch()

Over, 更多功能详见文档,小伙伴们开始愉快的搞事情吧!

关于 Goravel

Goravel 是一个功能完备、具有良好扩展能力的 Web 应用程序框架。 作为一个起始脚手架帮助 Golang 开发者快速构建自己的应用。

项目地址:https://github.com/goravel/goravel

文档地址:www.goravel.dev

golang横-500.png


有疑问加站长微信联系(非本文作者))

280

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK