go-events实现了一种处理event
的机制,其核心概念是Sink
(定义在event.go
):
// Event marks items that can be sent as events.
type Event interface{}
// Sink accepts and sends events.
type Sink interface {
// Write an event to the Sink. If no error is returned, the caller will
// assume that all events have been committed to the sink. If an error is
// received, the caller may retry sending the event.
Write(event Event) error
// Close the sink, possibly waiting for pending events to flush.
Close() error
}
可以把Sink
想象成一个“池子”,它提供了2
个方法:Write
往“池子”里发消息,Close
是不用时关闭这个“池子”。 其它几个文件其实都是围绕Sink
做文章,构造出各种功能。举个例子:
package main
import (
"fmt"
"github.com/docker/go-events"
"time"
)
type eventRecv struct {
name string
}
func (e *eventRecv)Write(event events.Event) error {
fmt.Printf("%s receives %d\n", e.name, event.(int))
return nil
}
func (e *eventRecv)Close() error {
return nil
}
func createEventRecv(name string) *eventRecv {
return &eventRecv{name}
}
func main() {
e1 := createEventRecv("Foo")
e2 := createEventRecv("Bar")
bc := events.NewBroadcaster(e1, e2)
bc.Write(1)
bc.Write(2)
time.Sleep(time.Second)
}
执行结果如下:
Foo receives 1
Bar receives 1
Foo receives 2
Bar receives 2
NewBroadcaster
作用是把一个event
发送到多个Sink
。
再看一个使用NewQueue
的例子:
package main
import (
"fmt"
"github.com/docker/go-events"
"time"
)
type eventRecv struct {
name string
}
func (e *eventRecv)Write(event events.Event) error {
fmt.Printf("%s receives %d\n", e.name, event)
return nil
}
func (e *eventRecv)Close() error {
return nil
}
func createEventRecv(name string) *eventRecv {
return &eventRecv{name}
}
func main() {
q := events.NewQueue(createEventRecv("Foo"))
q.Write(1)
q.Write(2)
time.Sleep(time.Second)
}
执行结果如下:
Foo receives 1
Foo receives 2
有疑问加站长微信联系(非本文作者)