Symfony messenger and AWS SNS/SQS
Could be useful decoupling applications parts in order to allow asynchronous processing especially for heavy tasks.
Lets suppose that, when an order is collected from our application we would send a message to a queue that will be handled from a consumer at some point.
to do so we will dispatch a message from symfony to an aws SNS topic and to the same topic we will attach a subscriber that will be a SQS queue
Let’s start installing symfony messenger
composer require symfony/messenger
Then we also need to install messenger-enqueue-transport to use SNS transport
composer require sroze/messenger-enqueue-transport enqueue/sns
now lets configure the newly installed components
config/packages/messenger.yaml
framework:
messenger:
transports:
sns:
dsn: ‘enqueue://testsns?topic[name]=test’
serializer: messenger.transport.symfony_serializer routing:
‘App\Message\SimpleOrder’: sns serializer:
symfony_serializer:
format: json
config/packages/enqueue.yamlconfig/packages/enqueue.yaml
enqueue:
testsns:
transport:
dsn: “sns:”
connection_factory_class: ‘Enqueue\Sns\SnsConnectionFactory’
key: ‘%env(AWS_KEY)%’
secret: ‘%env(AWS_SECRET)%’
region: ‘%env(AWS_TARGET_REGION)%’
client: ~
with those we are basically sending to a sns topic called “test” all the dispatched App\Message\SimpleOrder using the standard symfony serializer to convert the message into json format.
Remember to give the right permission policies to the corresponding aws user, and to subscribe the SQS queue to the SNS topic.
Create the SimpleOrder
class SimpleOrder
{
protected $message; public function __construct(string $message)
{
$this->message = $message;
} public function getMessage()
{
return $this->message;
}
}
and now we are ready for dispatching messages from our symfony application
$this->bus->dispatch(new SimpleOrder(‘This is a simple order message’));
let’s have a look to our queue:
the message is there, ready to be consumed.
it is quite simple to start to enjoy decoupling a symfony application leveraging the symfony messenger component and clouds(aws) services. Of course the enqueue package support a lots of transports like Kafka and Google PubSub.
In the next article we are going to explore how to consume messages from sqs queue, so stay tuned and happy coding!