我正在尝试学习 GO 并尝试不同的概念。现在我正在尝试 PubSub 方法,但在应用程序中。我有一个EventBus,我正在尝试通过依赖注入传递实例。但是,当我运行该应用程序时,什么也没有发生。主要的package mainimport ( "github.com/asaskevich/EventBus" modelA "interfaces/internal/modelA" modelB "interfaces/internal/modelB")func main() { bus := EventBus.New() a := &modelA.Bus{EventBus: bus} a.Send() b := &modelB.Bus{ EventBus: bus, } b.Receive()}内部/模型Apackage modelAimport ( "fmt" "github.com/asaskevich/EventBus")type Bus struct { EventBus EventBus.Bus}type ModelAService interface { Run() Send()}func calculator(a int, b int) { fmt.Printf("ModelA "+"%d\n", a+b)}func (bus *Bus) Receive() { err := bus.EventBus.Subscribe("testMessageFromB", calculator) if err != nil { fmt.Printf("Error Receiving message...") }}func (bus *Bus) Send() { bus.EventBus.Publish("testMessageFromA", 33, 33)}内部/模型Bpackage modelBimport ( "fmt" "github.com/asaskevich/EventBus")type Bus struct { EventBus EventBus.Bus}type ModelBService interface { Run() Send()}func calculator(a int, b int) { fmt.Printf("ModelB "+"%d\n", a+b)}func (bus *Bus) Receive() { err := bus.EventBus.Subscribe("testMessageFromA", calculator) if err != nil { fmt.Printf("Error Receiving message...") }}func (bus *Bus) Send() { bus.EventBus.Publish("testMessageFromB", 33, 60)}
1 回答
呼唤远方
TA贡献1856条经验 获得超11个赞
您需要先订阅主题
,然后发布(执行为主题定义的回调)。
尝试这样的事情:
func main() {
bus := EventBus.New()
a := &modelA.Bus{EventBus: bus}
b := &modelB.Bus{EventBus: bus}
b.Receive() // Subscribe
a.Send() // Publish
// Unsubscribe
}
另见示例:
func calculator(a int, b int) {
fmt.Printf("%d\n", a + b)
}
func main() {
bus := EventBus.New();
bus.Subscribe("main:calculator", calculator);
bus.Publish("main:calculator", 20, 40);
bus.Unsubscribe("main:calculator", calculator);
}
我的调试结构和输出:
脚注:为了清楚起见,
您可以将b.Receive()
to b.Subscribe()
和a.Send()
to重命名a.Publish()
。
另见gRPC:
- 1 回答
- 0 关注
- 216 浏览
添加回答
举报
0/150
提交
取消