Publish-Subscribe pattern(pub/sub) is a communication mechanism frequently used by micro-service architecture. AWS Simple Notification Service(SNS) and Simple Queue Service(SQS) are great services that help businesses to build scalable and fault tolerant systems bringing the flexibility and reliability of enterprise message-oriented applications*.*
Let’s build a micro-service architecture that implements SQS, SNS and Laravel, We are going to need a name for this new awesome architacture, let’s call it Service A, let’s also create our AWS services needed, we are going to need a SNS topic, let’s name it sns_service_a_message and a SQS queue sqs_service_a.
Create a SNS topic:
Create a new SQS and subscribe to the SNS topic previously created.
Create a IAM user with AmazonSQSFullAccess permission.
Also make sure that you have your AWS credential configured, please read this page if you need help doing so.
Laravel
Now that we have our Amazon Web Services SQS, SNS configured and our IAM user created, let’s move on on how to subscribe and consume messages with Laravel.
We are gonna make use of the aws/aws-sdk-php laravel package as it makes it easy for developers to access Amazon Web Services from within PHP code.
Now let’s see Laravel consuming SQS messages, for simplicity we are going to create a helper class that is going to configure the queueURL and it is going to create an SQSClient on its construct method and will receiveMessages when its handle function is called.
And then we are just going to call this class from the API, in your routes/api.php add the code snippet below:
Route::get('sqs', function(){
(new ProcessMessageHelper())->handle();
});
When a message is sent to t our SQS and we hit the URL(http://127.0.0.1:8000/api/sqs) we should see a payload like the below:
array(5) {
\["MessageId"\]=>
string(36) "d26c79b2-b735-4d0d-b49b-3c26138de161"
\["ReceiptHandle"\]=>
string(412) "AQEBtts0V271WPq7l9Ut4CKNSDIlX9ljNsrl6JylEZkFk3ar8X9U8u5UtnXnTq4FH4IJvyMtdrKCLv4q+L2mkrg7SuEp9hBewy5umR7L5sbV2QzNMM2gZ8fOKi37i0VRVXiq9lX6JB/K4ssn4cx2Y51UECmo7c/yoTYUDkw0tqwnSic9KsYFXBtsydCZ3WmIVANkjYN53S9fIw1tXZLTEI2zjdioaSP6hkOfY+b5oHhFXOAU7DVa00JQorZ040sJ7aC9JywqGALhx/ORBRiHfA8G5Auk2SL77Cx+EpZvmZsY1T7UI1N5UPlCuIvAg6LYh7cNqAFILKYRRKvSGryMGxhDTcXYhWrSPXzoUMK2nNeGjLkGls2f+T5ag1EWHzaSiShTdZHQm1k9EDJRrywf4U/lqg=="
\["MD5OfBody"\]=>
string(32) "b2f79cdd35aaa0534584d0f29fbcff1e"
\["Body"\]=>
string(14) "hello there!!!"
\["Attributes"\]=>
array(1) {
\["SentTimestamp"\]=>
string(13) "1577917862259"
}
}
If you would like to take this implementation a little further you may want to create a worker that checks for SQS messages in the background instead of relying on a URL.
For a complete working repo please feel free to take a look at and play around with the repo -> https://github.com/apuello/sqs-laravel
Don't forget to follow me:
Twitter: @monkeyswipes
Medium: @monkeyswipes
Top comments (0)