eventbus

package module
v0.0.0-...-199659d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2017 License: Apache-2.0 Imports: 6 Imported by: 2 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

eventbus

中文介绍

License Go Report Card GoDoc Build Status Coverage Status

Brief

Eventbus is event framework for in-memory event management.

  • Fault isolation
  • Asynchronous event dispatching
  • Filter support:enable log 、intercept、monitor messages.
  • [todo]Multicasting events
  • [todo]State monitor:enable monitor the topic statistic.
  • [todo]Topic matchers:enable a subscriber to subscribe many topics

Just Three Steps

  1. define events
type message struct { /* Additional fields if needed */ }

We can ignore this step if basic type ,such as string、int、uint etc.. 2. Prepare subscribers: Declare your subscribing method without Mutex for multithreading,

//we can use any method name to  handle event 
func  HandleMsg(msg interface{}) {/* Do something */};

//...
func main(){
    eventbus.Default.Subscribe("topic",HandleMsg)
    //...
}
  1. Push events
eventbus.Default.Push("topic",this is test msg!")

Can I use it?

The implementation is still in beta, we are using it for our production already. But the API change will be happen until 1.0.

Examples

base function

this code show eventbus basic function:

  1. fault isolation
  2. the subscription object itself is unsubscribed
  3. eventbus stop gracefull
type CountMessage struct {
	Num int
}

type Consumer struct {
	testNilMap map[int32]struct{}
	counter    int
	sub        *eventbus.Subscribe
}

func (c *Consumer) HandleMessage(message interface{}) {
	cMsg, ok := message.(CountMessage)
	if !ok {
		return
	}
	c.counter++
	//When a condition is met, performe the operation which causes the crash
	if cMsg.Num == 6 {
		c.testNilMap[2] = struct{}{}
	} else {
		fmt.Printf("Num:=%v  \n", cMsg.Num)

	}

	if c.counter > 9 {
		fmt.Println("consumer unscribe topic,and cannot receive any message later.")
		c.sub.Unscribe()
	}
}

//this code show eventbus basic func此代码演示消费者订阅的基本功能:
// 1.fault isolation
// 2.the subscription object itself is unsubscribed
// 3.eventbus stop gracefull
func main() {
	var (
		eb    = eventbus.Default()
		topic = "add"
	)
	consumer := &Consumer{}
	sub, _ := eb.Subscribe(consumer.HandleMessage,topic)
	consumer.sub = sub

	fmt.Println("send 10 messages, Num from 0 to 9")
	time.Sleep(time.Second)
	for i := 0; i < 10; i++ {
		time.Sleep(time.Millisecond * 500)
		eb.Publish(topic, CountMessage{i})
	}

	time.Sleep(time.Second)
	fmt.Println("send 10 messages, Num from 10 to 19")
	//those messages cannot received by consumer,because it unsubscribe this topic
	for i := 10; i < 20; i++ {
		time.Sleep(time.Millisecond * 200)
		eb.Publish(topic, CountMessage{i})
	}

	eb.StopGracefull()
}
topic message filter

this code show how to use filter。therefor,we can log 、intercept、monitor etc with filter.

type CountMessage struct {
	X, Y int
}

//DivisorJudgment implement struct of "Filter"
type DivisorJudgment struct {
}

func (m *DivisorJudgment) Receive(message interface{}) (newMsg interface{}, proceed bool) {
	msg, ok := message.(CountMessage)
	if !ok {
		return nil, false
	}
	//determines whether the divisor is zero。if it's ,catch it.
	if msg.Y == 0 {
		fmt.Printf("[Filter] [X/Y]:[%2d/%2d]= ,zero the dividend \n", msg.X, msg.Y)
		return nil, false
	}
	return msg, true
}

type Consumer struct {
	testNilMap map[int32]struct{}
}

func (c *Consumer) Div(message interface{}) {
	cMsg, ok := message.(CountMessage)
	if !ok {
		return
	}
	if cMsg.X == 95 {
		c.testNilMap[2] = struct{}{}
	} else {
		//fmt.Printf("[Consumer] [X/Y]:[%2d/%2d]= %d \n", cMsg.X, cMsg.Y, cMsg.X/cMsg.Y)
		_ = cMsg.X / cMsg.Y

	}
}

//this code show how can use filter to intercept message!
func main() {
	var (
		r        = rand.New(rand.NewSource(time.Now().UnixNano()))
		eb       = eventbus.New()
		consumer = &Consumer{}
		topic    = "T"
	)
	eb.InitTopic(topic, &Watcher{})
	eb.Subscribe(consumer.Div, topic)
	eb.LoadFilter(topic, &DivisorJudgment{})

	fmt.Println("catch zero divisor by filter.")

	//0...49,catch zero divisor by [watcher];and 50...99,no watcher.
	for i := 0; i < 100; i++ {
		eb.Push(topic, CountMessage{i, r.Intn(5)})
		time.Sleep(time.Millisecond * 50)
		if i == 50 {
			fmt.Printf("[topic statics]:%+v \n", eb.Statistic(topic)[0])

			fmt.Println("recover collapse by eventbus.")
			eb.UnloadFilter(topic, &DivisorJudgment{})
		}
	}
	eb.StopGracefull()
	fmt.Printf("[topic statics]:%+v \n", eb.Statistic(topic)[0])
}

more examples

Documentation

Overview

package Eventbus is an enhanced version of the standalone pub-sub asynchronous messaging framework. The system provides a large throughput of stand-alone message engine frameworks. In addition to the general news subscription, the release of the functional support, but also can be used for server-side ECS application scenarios. Has the following features: 1. Large throughput, 1000wQPS 2. Topic [filter] support 3. Statistics plug-in support

Package eventbus is a simple subscription service module that provides asynchronous message distribution based on single computer memory

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnvaliableTopic = errors.New("topic unvaliable.")
	ErrDuplicateTopic  = errors.New("topic duplicated.")
	ErrClosed          = errors.New("eventbus closed.")
)

Functions

This section is empty.

Types

type Bus

type Bus struct {
	// contains filtered or unexported fields
}

Bus is a subscription service module

func Default

func Default() *Bus

Default get default init Bus

func New

func New() *Bus

New create a eventbus

func (*Bus) InitTopic

func (bus *Bus) InitTopic(topicName string, statics Statistics) error

InitTopic use this method to set statics before Subscribe if we need to set

func (*Bus) LoadFilter

func (bus *Bus) LoadFilter(topic string, filter Filter) error

func (*Bus) Push

func (bus *Bus) Push(topicName string, message interface{}) error

Push push a message to topic mailbox

func (*Bus) Statistic

func (bus *Bus) Statistic(names ...string) []Statistics

func (*Bus) Stop

func (bus *Bus) Stop()

Stop immediately stop the execution of eventbus ,dropping all unreceived msg in topic mailbox

func (*Bus) StopGracefull

func (bus *Bus) StopGracefull()

StopGracefull block for stoping eventbus until all messages are received by the consumer

func (*Bus) Subscribe

func (bus *Bus) Subscribe(handle CallFunc, topicNames ...string) (Subscribe, error)

Subscribe 订阅主题,并返还供客户端使用的主题应用,可用来撤销或查看订阅情况

func (*Bus) UnloadFilter

func (bus *Bus) UnloadFilter(topic string, filter Filter) error

type CallFunc

type CallFunc func(message interface{})

CallFunc definition of the consumer function which eventbus call

type Filter

type Filter interface {
	//HandleMessage handle message and return it's judge ,
	// if one or more Filter return FALSE ,the consumers can not receive it
	HandleMessage(message interface{}) (proceed bool)
}

Filter monitor the topic input message .one topic can add many Filter. the Filter will be invoke before the topic send message to consumer.

type Statistics

type Statistics interface {
	SetTopicName(topciName string)
	TopicSubscribe()
	TopicUnscribe()
	FilterLoad()
	FilterUnload()
	MessagePushed(message interface{})
	MessageReceived(message interface{})
}

type Subscribe

type Subscribe interface {
	//remove all message handle from subscribed topics
	UnscribeAll()
	//remove  message handle from subscribed topic
	// will get error if this topic is not subscribed
	Unscribe(topicName string) error
	//get subscribed topics
	Topics() []string
}

type Topic

type Topic struct {
	Name string
	// contains filtered or unexported fields
}

Topic 是一个订阅消息的运行对象定义,封装了邮箱和消费者

func NewTopic

func NewTopic(topicName string, statitic Statistics) *Topic

NewTopic topic constructor

func (*Topic) Close

func (topic *Topic) Close()

Close close topic until all messages have been sent to the registered client.

func (*Topic) Info

func (topic *Topic) Info() Statistics

func (*Topic) PostCmdMessage

func (topic *Topic) PostCmdMessage(message interface{})

func (*Topic) PostUserMessage

func (topic *Topic) PostUserMessage(message interface{})

func (*Topic) ReceiveCmdMessage

func (topic *Topic) ReceiveCmdMessage(message interface{})

func (*Topic) ReceiveUserMessage

func (topic *Topic) ReceiveUserMessage(message interface{})

Directories

Path Synopsis
example
benchmark command
simple command
stopgraceful command
watcher command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL