這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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 mainimport ( "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 1Bar receives 1Foo receives 2Bar receives 2
NewBroadcaster
作用是把一個event
發送到多個Sink
。
再看一個使用NewQueue
的例子:
package mainimport ( "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 1Foo receives 2