Home  >  Article  >  Backend Development  >  Using the Heartbeats pattern in Golang

Using the Heartbeats pattern in Golang

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 06:08:30926browse

Utilizando o pattern Heartbeats em Golang

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,
) (<-chan struct{}, <-chan string) {

    heartbeats := make(chan struct{}, 1)
    names := make(chan string)

    go func() {
        defer close(heartbeats)
        defer close(names)

        beat := time.NewTicker(interval)
        defer beat.Stop()

        for letra := range letras {
            select {
            case <-ctx.Done():
                return
            case <-beat.C:
                select {
                case heartbeats <- struct{}{}:
                default:
                }
            case names <- dicionario[letra]:
                lether := dicionario[letra]
                fmt.Printf("Letra: %s \n", lether)

                time.Sleep(3 * time.Second) // Simula um tempo de espera para vermos o hearbeats
            }
        }
    }()

    return heartbeats, names
}

Importing Dependencies

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,
) (<-chan struct{}, <-chan string) {

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.

Channels

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 <-ctx.Done():
            return
        case <-beat.C:
            select {
            case heartbeats <- struct{}{}:
            default:
            }
        case names <- dicionario[letra]:
            lether := dicionario[letra]
            fmt.Printf("Letra: %s \n", lether)

            time.Sleep(3 * time.Second) // Simula um tempo de espera para vermos o hearbeats
        }
    }
}()

return heartbeats, names

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:

  • case <-ctx.Done(): If the context is canceled, the function exits immediately, using the return.
  • statement
  • case <-beat.C: If the beat ticker sends a value, the goroutine tries to send an empty struct to the heartbeats channel using a select with an empty default.
  • case names <- dictionary[letter]: If a letter is received, the goroutine obtains the name of the corresponding letter from the dictionary dictionary, sends it to the names channel, prints the letter to the screen using the fmt package and waits for three seconds before proceeding to the next character. This simulated wait is so that we can see the “heartbeats” being sent.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn