A lightweight eventbus that simplifies communication between goroutines,

English | 简体中文

eventbus

A lightweight eventbus that simplifies communication between goroutines, it supports synchronous and asynchronous message publishing.

Installation

Make sure that go(version 1.18+) is installed on your computer. Type the following command:

go get github.com/werbenhu/eventbus

Import package in your project

import (
	"github.com/werbenhu/eventbus"
)

What's eventbus?

EventBus supports both synchronous and asynchronous message publication. it uses a Copy-On-Write map to manage handlers and topics, so it is not recommended for use in scenarios with a large number of frequent subscriptions and unsubscriptions.

Asynchronous Way

In EventBus, each topic corresponds to a channel. The Publish() method pushes the message to the channel, and the handler in the Subscribe() method handles the message that comes out of the channel.If you want to use a buffered EventBus, you can create a buffered EventBus with the eventbus.NewBuffered(bufferSize int) method, which will create a buffered channel for each topic.

Synchronous Way

In the synchronous way, EventBus does not use channels, but passes payloads to subscribers by calling the handler directly. To publish messages synchronously, use the eventbus.PublishSync() function.

eventbus example

package main

import (
	"fmt"
	"time"

	"github.com/werbenhu/eventbus"
)

func handler(topic string, payload int) {
	fmt.Printf("topic:%s, payload:%d\n", topic, payload)
}

func main() {
	bus := eventbus.New()

	// Subscribe to a topic. Returns an error if the handler is not a function.
	// The handler function must have two parameters: the first parameter must be of type string,
	// and the second parameter's type must match the type of `payload` in the `Publish()` function.
	bus.Subscribe("testtopic", handler)

	// Publish a message asynchronously.
	// The `Publish()` function triggers the handler defined for the topic, and passes the `payload` as an argument.
	// The type of `payload` must match the type of the second parameter in the handler function defined in `Subscribe()`.
	bus.Publish("testtopic", 100)

	// Publish a message synchronously.
	bus.PublishSync("testtopic", 200)

	// Wait a bit to ensure that subscribers have received all asynchronous messages before unsubscribing.
	time.Sleep(time.Millisecond)
	bus.Unsubscribe("testtopic", handler)

	// Close the event bus.
	bus.Close()
}

Using the global singleton object of EventBus

To make it more convenient to use EventBus, there is a global singleton object for EventBus. You can initialize this singleton object by calling eventbus.InitSingleton(). The internal channel of this object is unbuffered, and you can directly use eventbus.Subscribe(), eventbus.Publish(), and eventbus.Unsubscribe() to call the corresponding methods of the singleton object.

func handler(topic string, payload int) {
	fmt.Printf("topic:%s, payload:%d\n", topic, payload)
}

func main() {

	// Initialize the singleton object
	eventbus.InitSingleton()

	// eventbus.Subscribe() will call the global singleton's Subscribe() method
	eventbus.Subscribe("testtopic", handler)

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		// Asynchronously publish messages
		for i := 0; i < 100; i++ {
			// eventbus.Publish() will call the global singleton's Publish() method
			eventbus.Publish("testtopic", i)
		}
		// Synchronously publish messages
		for i := 100; i < 200; i++ {
			eventbus.PublishSync("testtopic", i)
		}
		wg.Done()
	}()
	wg.Wait()

	time.Sleep(time.Millisecond)
	// eventbus.Unsubscribe() will call the global singleton's Unsubscribe() method
	eventbus.Unsubscribe("testtopic", handler)

	// eventbus.Close() will call the global singleton's Close() method
	eventbus.Close()
}

Use Pipe instead of channel

Pipe is a wrapper for a channel without the concept of topics, with the generic parameter corresponding to the type of the channel. eventbus.NewPipe[T]() is equivalent to make(chan T). Publishers publish messages, and subscribers receive messages. You can use the Pipe.Publish() method instead of chan <-, and the Pipe.Subscribe() method instead of <-chan.

If there are multiple subscribers, each subscriber will receive every message that is published.If you want to use a buffered channel, you can use the eventbus.NewBufferedPipe[T](bufferSize int) method to create a buffered pipe.Pipe also supports synchronous and asynchronous message publishing. If you need to use the synchronous method, call Pipe.PublishSync().

pipe example

func handler1(val string) {
	fmt.Printf("handler1 val:%s\n", val)
}

func handler2(val string) {
	fmt.Printf("handler2 val:%s\n", val)
}

func main() {
	pipe := eventbus.NewPipe[string]()
	pipe.Subscribe(handler1)
	pipe.Subscribe(handler2)

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		for i := 0; i < 100; i++ {
			pipe.Publish(strconv.Itoa(i))
		}
		for i := 100; i < 200; i++ {
			pipe.PublishSync(strconv.Itoa(i))
		}
		wg.Done()
	}()
	wg.Wait()

	time.Sleep(time.Millisecond)
	pipe.Unsubscribe(handler1)
	pipe.Unsubscribe(handler2)
	pipe.Close()
}
Similar Resources

go.pipeline is a utility library that imitates unix pipeline. It simplifies chaining unix commands (and other stuff) in Go.

go.pipeline go.pipeline is a utility library that imitates unix pipeline. It simplifies chaining unix commands (and other stuff) in Go. Installation g

May 8, 2022

The Fabric Smart Client is a new Fabric Client that lets you focus on the business processes and simplifies the development of Fabric-based distributed application.

Fabric Smart Client The Fabric Smart Client (FSC, for short) is a new Fabric client-side component whose objective is twofold. FSC aims to simplify th

Dec 14, 2022

alonzo-testnet simplifies deploying a private alonzo testnet.

alonzo-testnet alonzo-testnet simplifies deploying a private alonzo testnet. SundaeSwap heavily leverages AWS and consequently, this tooling has been

Oct 5, 2022

fastcache is an HTTP response caching package that plugs into fastglue that simplifies

fastcache fastcache is a simple response caching package that plugs into fastglue. The Cached() middleware can be wrapped around fastglue GET handlers

Apr 5, 2022

Go package simplifies nullable fields handling using Go Generics.

Go Nullable with Generics Go package simplifies nullable fields handling with Go Generics. Package gonull provides a generic Nullable type for handlin

May 7, 2023

Our notification system simplifies the process of sending notifications via email, SMS, and push notifications for multiple applications. It supports multiple providers, customizable templates, and is easy to integrate into any application.

Our notification system simplifies the process of sending notifications via email, SMS, and push notifications for multiple applications. It supports multiple providers, customizable templates, and is easy to integrate into any application.

Simplify Notification Management with Customizable Templates and Multi-Provider Integration ⭐️ Why Envoyer Nowadays, notifications play a crucial role

May 11, 2023

More effective network communication, two-way calling, notify and broadcast supported.

ARPC - More Effective Network Communication Contents ARPC - More Effective Network Communication Contents Features Performance Header Layout Installat

Dec 22, 2022

🔊Minimalist message bus implementation for internal communication

🔊 Bus Bus is a minimalist event/message bus implementation for internal communication. It is heavily inspired from my event_bus package for Elixir la

Jan 3, 2023

Interblockchain communication protocol (IBC) implementation in Golang.

ibc-go Interblockchain communication protocol (IBC) implementation in Golang built as a SDK module. Components Core The core/ directory contains the S

Jan 7, 2023

A game server side framework with both web API and realtime communication.

HAYABUSA Framework Hayabusa is a server side framework for Japan-like social games. Easy to understand and use for beginners Powerful controller, flex

May 21, 2022

Async peer communication protocol & library

Async peer communication protocol & library

Gotalk exists to make it easy for programs to talk with one another over the internet, like a web app coordinating with a web server, or a bunch of programs dividing work amongst each other.

Jan 5, 2023

A library for communication with solar power inverters of the RCT power brand, not endorsed by or affiliated with the eponymous company.

rct A library for communication with solar power inverters of the RCT power brand. Tested with the RCT PS 6.0 solar power inverter, battery and grid p

Dec 21, 2022

Transport to allow go-libp2p applications to natively use i2p for communication

I2P Transport for go-libp2p This library can be used to build go-libp2p applications using the i2p network. Look at transport_test.go for example usag

Sep 15, 2022

BrisGolang is a Go implementation of the game of briscola using the WebSocket protocol for client/server communication.

BrisGolang BrisGolang is a Go implementation of the game of briscola using the WebSocket protocol for client/server communication. Usage You can play

Nov 1, 2021

Simple, fast and safe cross-platform linear binary stream communication protocol. AES key exchange based on ecc secp256k1

FFAX Protocol 2 dev 简体中文 Welcome to FFAX Protocol v2 Quick start go get github.com/RealFax/FFAX func example() { listener, err := net.Listen("tcp",

Mar 21, 2022

Simple & Primitive multi client communication system

What is this Simple & Primitive multi client communication system. e.g. chat system for larning Supported Broadcast message Unicast message Not Suppor

Dec 3, 2021

Episode VII: The DB Awakens (fully stablished JSON communication system)

APITrials0.7 Episode VII: The DB Awakens (fully stablished JSON communication system) Captain's log: Im too deep into the rabbit hole now. This seems

Jan 10, 2022

ACN - Agent Communication Network

The libp2p_node is an integral part of the ACN. ACN - Agent Communication Network The agent communication network (ACN) provides a system for agents t

Sep 28, 2022

Furui - A process-based communication control system for containers

furui Communication control of the container runtime environment(now only docker

Mar 26, 2022
go-ddns - lightweight GoDaddy dyndns updater

go-ddns - lightweight GoDaddy dyndns updater A no nonsense DynDNS updater for your GoDaddy domains Configuration Configuration is done through environ

Oct 7, 2021
A single-binary cross-platform lightweight client/server connection testing tool.

conntest A single-binary cross-platform lightweight client/server connection testing tool. Currently supports L7 TCP (HTTP). Configuration Options con

Jan 13, 2022
lightweight, self-service AWS IAM management
lightweight, self-service AWS IAM management

Contents Overview Architecture Prerequisites Workflow What groups exist? Who do I ask for access? What groups am I in? How do I add group members? How

Jan 16, 2022
Zero Trust Network Communication Sentinel provides peer-to-peer, multi-protocol, automatic networking, cross-CDN and other features for network communication.
Zero Trust Network Communication Sentinel provides peer-to-peer, multi-protocol, automatic networking, cross-CDN and other features for network communication.

Thank you for your interest in ZASentinel ZASentinel helps organizations improve information security by providing a better and simpler way to protect

Nov 1, 2022
[Go] Lightweight eventbus with async compatibility for Go

EventBus Package EventBus is the little and lightweight eventbus with async compatibility for GoLang. Installation Make sure that Go is installed on y

Jan 1, 2023
[Go] Lightweight eventbus with async compatibility for Go

EventBus Package EventBus is the little and lightweight eventbus with async compatibility for GoLang. Installation Make sure that Go is installed on y

Jan 3, 2023
[Go] Lightweight eventbus with async compatibility for Go

[Go] Lightweight eventbus with async compatibility for Go

Jan 3, 2023
Mizu - API traffic viewer for Kubernetes enabling you to view all API communication between microservices
Mizu - API traffic viewer for Kubernetes enabling you to view all API communication between microservices

The API Traffic Viewer for Kubernetes A simple-yet-powerful API traffic viewer f

Jan 9, 2023
Communication channels between Bitcoin users, agents, and services.

Channels Channels are a set of protocols designed to facilitate communication between users, agents, and services. Channels work on top of “peer chann

Dec 15, 2022
Tabular simplifies printing ASCII tables from command line utilities

tabular Tabular simplifies printing ASCII tables from command line utilities without the need to pass large sets of data to it's API. Simply define th

Oct 28, 2022