On March 31 2022, I gave a talk at Conf42:Golang about using Go in an event-driven architecture entitled "Gopher in an Event Driven Playground". You can check out the talk here or read along to know more about event-driven systems and how different messaging protocols are used in Go!
What's all the hype about?
For all of us Go enthusiasts out there, we truly understand the beauty of using Go in applications and microservices because of its lightweight, high performance, and elegant syntax, to name just a few (let the debate start! π₯).
So imagine using your favourite programming language (yes, that is Go) with your favourite architecture (yes, that event-driven architecture) - where do you start? Carry on and read further to explore.
Hold on, what is an event-driven architecture (EDA)?
Glad you asked! There are loads of resources online that talk about EDA. At its core, an event-driven architecture involves asynchronous communication between applications via publishing and subscribing to events over an event broker using a messaging protocol.
Some examples of messaging protocols include open standard and open source protocols such as MQTT, AMQP, and JMS.
To delve more into event-driven architecture and explore different use-cases, check out this page on What is Event-Driven Architecture.
I also wrote a blog post talking about how I built an event-driven NodeJS app on real-time COVID-19 data streams, highlighting the advantages of event-driven architecture, if you want to explore it further:
Let's start with creating a new directory and initializing go mod. In a new terminal window, execute the following commands:
mkdirfunWithEDA&&cd"$_"gomodinitGoEDA
MQTT
As per definition: "MQTT is an OASIS standard messaging protocol for the Internet of Things (IoT). It is designed as an extremely lightweight publish/subscribe messaging transport that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth"
The Eclipse Paho project provides open source, mainly client side, implementations of MQTT in a variety of programming languages. For today's fun coding session, we will be using the Eclipse Paho MQTT Go client.
Install the Paho MQTT Go library
go get github.com/eclipse/paho.mqtt.golang
Create a new file and open it with your favourite IDE. I named my file go_mqtt.go.
Initialize the file and import the necessary libraries
We will need to define the callback functions as follows
varmessageHandlermqtt.MessageHandler=func(clientmqtt.Client,msgmqtt.Message){fmt.Printf("Received message: %s from topic: %s\n",msg.Payload(),msg.Topic())}varconnectHandlermqtt.OnConnectHandler=func(clientmqtt.Client){options:=client.OptionsReader()fmt.Println("Connected to: ",options.Servers())}varconnectLostHandlermqtt.ConnectionLostHandler=func(clientmqtt.Client,errerror){fmt.Printf("Connect lost: %v",err)}
It is important to note that these functions will be triggered "on" particular actions. So for example, the messageHandler function will be triggered whenever the MQTT client receives a message via mqtt.MessageHandler.
And finally, define your publish and subscribe functions as follows:
funcpublish(clientmqtt.Client){num:=10fori:=0;i<num;i++{text:=fmt.Sprintf("Message %d",i)token:=client.Publish("conf42/go",0,false,text)token.Wait()time.Sleep(time.Second)}}funcsub(clientmqtt.Client){topic:="conf42/#"token:=client.Subscribe(topic,1,nil)token.Wait()fmt.Printf("Subscribed to topic: %s\n",topic)}
And that's it! Run the application and observe the results
go run go_mqtt.go
Solace PubSub+ Messaging API for Go
Now that you are an expert on messaging concepts with Go, let's take it up a notch and delve into a more advanced messaging API! We'll be using the Solace PubSub+ Messaging API for Go.
Install the Solace Native Go API
go get solace.dev/go/messaging
Create a new file and open it with your favourite IDE. I named my file solace_publisher.go.
messagingService,err:=messaging.NewMessagingServiceBuilder().FromConfigurationProvider(brokerConfig).Build()iferr!=nil{panic(err)}// Connect to the messaging sericeiferr:=messagingService.Connect();err!=nil{panic(err)}
Build a Direct Message Publisher and start it
// Build a Direct Message PublisherdirectPublisher,builderErr:=messagingService.CreateDirectMessagePublisherBuilder().Build()ifbuilderErr!=nil{panic(builderErr)}// Start the publisherstartErr:=directPublisher.Start()ifstartErr!=nil{panic(startErr)}
Publish messages in a loop
msgSeqNum:=0// Prepare outbound message payload and bodymessageBody:="Hello from Conf42"messageBuilder:=messagingService.MessageBuilder().WithProperty("application","samples").WithProperty("language","go")// Run forever until an interrupt signal is receivedgofunc(){fordirectPublisher.IsReady(){msgSeqNum++message,err:=messageBuilder.BuildWithStringPayload(messageBody+" --> "+strconv.Itoa(msgSeqNum))iferr!=nil{panic(err)}topic:=resource.TopicOf("conf42/solace/go/"+strconv.Itoa(msgSeqNum))// Publish on dynamic topic with dynamic bodypublishErr:=directPublisher.Publish(message,topic)ifpublishErr!=nil{panic(publishErr)}fmt.Println("Published message on topic: ",topic.GetName())time.Sleep(1*time.Second)}}()
This is the final application.
packagemainimport("fmt""os""os/signal""strconv""time""solace.dev/go/messaging""solace.dev/go/messaging/pkg/solace/config""solace.dev/go/messaging/pkg/solace/resource")funcmain(){// Configuration parametersbrokerConfig:=config.ServicePropertyMap{config.TransportLayerPropertyHost:"tcp://public.messaging.solace.cloud",config.ServicePropertyVPNName:"public",config.AuthenticationPropertySchemeBasicUserName:"conf42",config.AuthenticationPropertySchemeBasicPassword:"public",}messagingService,err:=messaging.NewMessagingServiceBuilder().FromConfigurationProvider(brokerConfig).Build()iferr!=nil{panic(err)}// Connect to the messaging sericeiferr:=messagingService.Connect();err!=nil{panic(err)}// Build a Direct Message PublisherdirectPublisher,builderErr:=messagingService.CreateDirectMessagePublisherBuilder().Build()ifbuilderErr!=nil{panic(builderErr)}// Start the publisherstartErr:=directPublisher.Start()ifstartErr!=nil{panic(startErr)}msgSeqNum:=0// Prepare outbound message payload and bodymessageBody:="Hello from Conf42"messageBuilder:=messagingService.MessageBuilder().WithProperty("application","samples").WithProperty("language","go")// Run forever until an interrupt signal is receivedgofunc(){fordirectPublisher.IsReady(){msgSeqNum++message,err:=messageBuilder.BuildWithStringPayload(messageBody+" --> "+strconv.Itoa(msgSeqNum))iferr!=nil{panic(err)}topic:=resource.TopicOf("conf42/solace/go/"+strconv.Itoa(msgSeqNum))// Publish on dynamic topic with dynamic bodypublishErr:=directPublisher.Publish(message,topic)ifpublishErr!=nil{panic(publishErr)}fmt.Println("Published message on topic: ",topic.GetName())time.Sleep(1*time.Second)}}()// Handle OS interruptsc:=make(chanos.Signal,1)signal.Notify(c,os.Interrupt)// Block until an OS interrupt signal is received.<-c// Terminate the Direct PublisherdirectPublisher.Terminate(1*time.Second)fmt.Println("\nDirect Publisher Terminated? ",directPublisher.IsTerminated())// Disconnect the Message ServicemessagingService.Disconnect()fmt.Println("Messaging Service Disconnected? ",!messagingService.IsConnected())}
And that's it! Run the publisher as follows
go run solace_publisher.go
Note: You can use the Solace PubSub+ TryMe tab to connect to the broker and subscribe to any topic you want. Subscribe to topic conf42/solace/>
Bonus! You can run a subscriber application in another terminal, subscribe to conf42/solace/>, and observe the results. You can find more about this on the SolaceSample github org.
Challenge! Run a publisher and a subscriber in the same application! π€―
This repository contains sample code to showcase how the Solace PubSub+ Go API could be used. You can find:
/patterns --> runnable code showcasing different message exchange patters with the PubSub+ Go API.
/howtos --> code snippets showcasing how to use different features of the API. All howtos are named how_to_*.go with some sampler files under sub-folders.
Using the Solace PubSub+ Event Broker, you can leverage the protocol translation and interoperability features. Even though the Go API was used to connect to the broker, you can use other Solace APIs and/or open standard protocols to connect to the broker and still have the microservices send and receive messages to each other.
Why use Solace native APIs??
You might be wondering, "Why should I use Solace native APIs as opposed to an open-standard open-source messaging protocol like MQTT?" Glad you asked! Check out this blog that talks about the advanced features you can get access to through using Solace's API?
If you want to see my colleagues and I during a live streaming session talking about EDA, the Solace PubSub+ Messaging API for Go, and coding (on LIVE television!), check out this event π
What about you?
I am curious to hear from the go community!
What is it about Golang that you enjoy?
Have you ever used Golang in an event-driven application?
What messaging protocols and/or open standards have you used?
What message brokers do you use?
Open to all sort of discussions, comments, and questions!