Implementing Heartbeats in Go for Application Monitoring
During my adventures in balancing Data & Software Engineer, I always look for something a little different in GoLang to study, understand how it works and apply it to more complex things than some basic traditional courses and articles that I find on the internet. In this short article, I will report and demonstrate how I implemented through Go Routines, the time package using Ticker to simulate the heartbeat ("I'm alive") of the application, in addition to the use of channels, etc.
It is not news to many that it is extremely important to ensure that whoever calls a certain function knows whether the function is taking time, processing, or in lock. That said, several other terminologies have emerged such as Trace, Metrics, connectivity, etc., which have been introduced in monitoring applications that in most cases use agents installed on the application servers that collect metrics and send them to interfaces that visualize all (or almost) the status of your application. Among these tools we have DataDog, NewRelic, Slack, Grafana, Jaeger, etc.
What Will We Have Here?
As I study and thinking about creating something quick and simple that addresses some more advanced Go concepts, I created a relatively simple application that makes use of the heartbeats pattern. Whoever is calling me receives the result and, at the same time, information whether I am still active or not. In a more advanced scenario, this may be interesting to customize what is actually an active application in terms of some business particularity, since a simple implementation of a Prometheus solves this case (is the application active? CPU, Memory, open goroutines ), but not with simultaneous and customizable feedback.
Hour of Code!
In terms of structure, I only created three files within my package with go mod:
- dictionary.go: Contains a dictionary of names for the function to search.
- task.go: Task that contains the function of scanning names from the dictionary and, at the same time, informing whether it is active or not via team.Ticker's channel beat.
- task_test.go: Performs a unit test of the function present in task.go to see both the response from the dictionary data and also feedback on whether the application is still Up!
dictionary.go
This part of the Go code is defining a variable called “dictionary” which is a map that associates rune-type characters with strings.
Each map entry is a key (rune) and a value (string). In the example below, the keys are lowercase letters of the alphabet and the values are names associated with each letter. For example, the letter ‘a’ is associated with the name “airton”, the letter ‘b’ is associated with the name “bruno”, and so on:
package heartbeat var dicionario = map[rune]string{ 'a': "airton", 'b': "bruno", 'c': "carlos", 'd': "daniel", 'e': "eduardo", 'f': "felipe", 'g': "gustavo", }
task.go
I explain better below after the complete code each part of the code:
package heartbeat import ( "context" "fmt" "time" ) func ProcessingTask( ctx context.Context, letras chan rune, interval time.Duration, ) ( <h3> Importing Dependencies </h3> <pre class="brush:php;toolbar:false">package heartbeat import ( "context" "fmt" "time" )
Here I have my heartbeat package that will be responsible for implementing a functionality that sends “heartbeats” at a specific time interval, while processing tasks. For this, I need context (Context Management), fmt (for string formatting) and time for time control.
Initial Function Definition
func ProcessingTask ( ctx context.Context, letras chan rune, interval time.Duration, ) ( <p>This is the definition of the ProcessingTask function that takes a ctx context, a letter channel (a channel that receives Unicode characters) and a time interval as arguments. The function returns two channels: a heartbeats channel that sends an empty struct for each “heartbeat” and a names channel that sends the name of the letter corresponding to each character received.</p> <h3> Channels </h3> <pre class="brush:php;toolbar:false">heartbeats := make(chan struct{}, 1) names := make(chan string)
These two lines create two channels: heartbeats is a buffer channel with capacity of one element and names is an unbuffered channel.
Go Routine that does the heavy lifting
go func() defer close(heartbeats) defer close(names) beat := time.NewTicker(interval) defer beat.Stop() for letra := range letras { select { case <p>This is an anonymous goroutine (or anonymous function that runs in a new thread) that executes the main logic of the ProcessingTask function. It uses a for-range loop to read characters from the letters channel. Inside the loop, use a select to choose an action to be performed from the available options:</p>
- case statement
- case
- case names
Finally, the function returns the heartbeats and names channels.
Testing the Application
task_test.go
package heartbeat var dicionario = map[rune]string{ 'a': "airton", 'b': "bruno", 'c': "carlos", 'd': "daniel", 'e': "eduardo", 'f': "felipe", 'g': "gustavo", }
Here I created a Go unit test for the ProcessingTask function that was explained previously. The TestProcessingTask test function creates a context with a timeout of 20 seconds and a channel of Unicode characters (letters). The anonymous goroutine then sends lyrics to the lyrics channel. The ProcessingTask function is then called with the context, Unicode character channel, and a time interval. It returns two channels, a heartbeat channel and a word channel.
The test function then runs an infinite loop with a select, which reads from three channels: the context, the heartbeat channel, and the word channel.
If the context is cancelled, the test loop is terminated. If a heartbeat is received, an “Application Up!” is printed to standard output. If a word is received, the test checks whether the word is present in the letter dictionary. If it is not present, the test fails and an error message is displayed.
Therefore, this unit test tests our ProcessingTask function, which receives characters from one channel, sends letter names to another channel and emits the “heartbeats” while running in a context in which I used a time limit. Ahhh... and it also checks if the names of the letters sent to the word channel are present in the dictionary.
My Conclusions
This Go code illustrates some important concepts of the Go language and unit tests:
- Context
- Goroutines
- Channels
- Unit tests (using select to monitor multiple channels)
Full project on my GitHub: https://github.com/AirtonLira/heartbeatsGolang
LinkedIn - Airton Lira Junior
The above is the detailed content of Using the Heartbeats pattern in Golang. For more information, please follow other related articles on the PHP Chinese website!

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
