Consuming Symfony Messenger messages with Go
Introduction
As an application grows, it has to process more and more messages, and that processing has to stay fast to keep performance high.
Symfony Messenger is great at dispatching messages. For the consuming side, I built Gosumer: it lets you process your Symfony Messenger messages in Go to improve your application's performance.
In this article, I'll explain what Gosumer does and show an example.
Introducing Gosumer
Gosumer is a Go package for consuming Symfony Messenger messages with Go code, instead of running the consumers in PHP.
It works with the PostgreSQL, AMQP and Redis transports.
You can find the source code of this package here; feel free to contribute or share your feedback!
Example: processing messages with Gosumer
Say you have a Symfony application that needs to process incoming messages quickly. With Gosumer, it takes a few lines of code:
package main
import (
"encoding/json"
"log"
"github.com/romaixn/gosumer"
)
type Message struct {
ID int `json:"id"`
Number int `json:"number"`
}
func main() {
database := gosumer.PgDatabase{
Host: "localhost",
Port: 5432,
User: "app",
Password: "!ChangeMe!",
Database: "app",
TableName: "messenger_messages",
}
err := gosumer.Listen(database, processMessage, Message{})
if err != nil {
log.Fatal(err)
}
}
func processMessage(message any, err chan error) {
log.Printf("Message received: %v", message)
jsonData, e := json.Marshal(message)
if e != nil {
log.Printf("Error marshalling message: %v", e)
err <- e
return
}
var msg Message
e = json.Unmarshal(jsonData, &msg)
if e != nil {
log.Printf("Error unmarshalling message: %v", e)
err <- e
return
}
log.Printf("Sum of %d and %d is %d", msg.ID, msg.Number, msg.ID+msg.Number)
err <- nil
return
}
In this example, we define a Message struct for the data in the incoming messages. It has the same structure as the message you defined on the Symfony side (PHP).
Then, we listen to all messages with the gosumer.listen function and process them with processMessage.
Once the message is processed and there are no errors, it's deleted from the database.
If an error occurs during processing, the message is not deleted and will be consumed again later.
I already have some ideas for improving the developer experience of the package. I've created a few issues that you can check out here.
Conclusion
Gosumer lets you consume Symfony Messenger messages with Go, which can make your application faster. You keep Symfony Messenger to dispatch messages, and Go does the processing.
The project is on GitHub: try it out and tell me what you think!
See you on GitHub! ⭐️