<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Roberto Massoni on Medium]]></title>
        <description><![CDATA[Stories by Roberto Massoni on Medium]]></description>
        <link>https://medium.com/@betomassoni?source=rss-3e02c8a08a4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G8GN52-XXR_JsOgHA5W5eg.jpeg</url>
            <title>Stories by Roberto Massoni on Medium</title>
            <link>https://medium.com/@betomassoni?source=rss-3e02c8a08a4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:51:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@betomassoni/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why GCP feels simpler than AWS (and when that’s a problem)]]></title>
            <link>https://medium.com/@betomassoni/why-gcp-feels-simpler-than-aws-and-when-thats-a-problem-95aaac34a8bd?source=rss-3e02c8a08a4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/95aaac34a8bd</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Roberto Massoni]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 18:14:01 GMT</pubDate>
            <atom:updated>2026-01-15T18:14:01.454Z</atom:updated>
            <content:encoded><![CDATA[<p>After working with <strong>both AWS and Google Cloud in production</strong>, this is a perception I personally had over time:</p><p><strong>GCP feels simpler than AWS.</strong></p><p>This didn’t come from reading docs or comparing service lists. It came from building real systems, dealing with IAM policies, querying data, running databases in production, and later confirming many of these impressions while studying for <strong>certifications on both platforms</strong>.</p><p>That simplicity is not accidental.<br> It shows up clearly when you look at some core services.</p><h3>Different ways of thinking</h3><p>AWS gives you <strong>a lot of options</strong>. GCP gives you <strong>a clearer path</strong>.</p><p>On AWS, there are often several services that can solve similar problems, each with its own configuration model. That gives you flexibility, but it also means more decisions and more chances to overcomplicate things.</p><p>On GCP, the platform usually pushes you toward a default way of doing things. You can go deeper if you need to, but you don’t have to from the start.</p><h3>BigQuery vs Athena / Redshift</h3><p>BigQuery is one of the clearest examples of why GCP feels simpler.</p><p>You load data.<br>You run queries.<br>You get results.</p><p>There’s very little setup involved. You don’t think about clusters or capacity upfront. The mental model is simple, and that matters a lot in real projects.</p><p>On AWS, Athena and Redshift are powerful, but they usually require more planning. You need to understand storage, query behavior, and sometimes performance tuning.</p><p>AWS gives you more control.<br>GCP gives you faster time to value.</p><h3>IAM: GCP vs AWS</h3><p>IAM is another place where the difference is very noticeable.</p><p>On GCP, IAM policies are usually easier to read and reason about. Roles are applied at clear levels (organization, folder, project, resource), and it’s often simpler to understand <em>why</em> someone has access.</p><p>AWS IAM is extremely powerful, but also easier to get wrong. Policies can become large and complex, and debugging permission issues often takes longer than expected.</p><h3>Cloud SQL vs RDS</h3><p>Most systems need a relational database.</p><p>Cloud SQL feels very straightforward. You create an instance, choose an engine, configure a few basics, and you’re ready. Backups, monitoring, and upgrades are easy to understand.</p><p>RDS is also very solid and widely used, but it offers more instance types, more options, and more decisions around networking and availability.</p><p>Once again:</p><ul><li>AWS gives flexibility</li><li>GCP gives simplicity</li></ul><h3>When simplicity helps</h3><p>For many teams, especially those without a dedicated platform or SRE team, simplicity matters a lot.</p><p>Clear defaults and fewer decisions:</p><ul><li>Make onboarding easier</li><li>Reduce operational effort</li><li>Make systems easier to understand</li><li>Help teams move faster</li></ul><p>This is where GCP often feels like a good fit.</p><h3>A common misunderstanding</h3><p>A lot of people think GCP feels simpler because it’s less powerful.</p><p>That’s not true.</p><p>The complexity is still there, it’s just hidden by the platform instead of being pushed onto the user.</p><p>This works very well if your goal is speed and clarity.<br> It works less well if your goal is full control.</p><h3>My personal opinion (after working with both)</h3><p>After years using <strong>AWS and GCP</strong>, and studying both deeply through <strong>certifications</strong>, my view is straightforward.</p><p><strong>AWS is an infinite toolbox.</strong><br><strong>GCP is a well-designed platform.</strong></p><p>AWS gives you <strong>maximum power</strong>, and <strong>maximum responsibility</strong>.<br>You can tune almost everything, but you also need to understand almost everything.</p><p>GCP gives you <strong>speed</strong>, and asks you to <strong>trust the platform</strong>.<br>Many decisions are already made for you, which reduces friction but also limits how much you can customize.</p><p>If I had to choose today:</p><ul><li><strong>AWS</strong> for extremely complex, legacy-heavy or heavily regulated environments</li><li><strong>GCP</strong> for modern, cloud-native products where speed and simplicity matter</li></ul><p>And no, this is not about which cloud is better.<br>It’s about <strong>which problem you are trying to solve</strong>.</p><h3>Final thoughts</h3><p>GCP is not “AWS but simpler.”<br>It’s a different way of designing cloud platforms.</p><p>Once you understand that, the choice becomes clearer and much less emotional.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95aaac34a8bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating GCP Pub/Sub with Kotlin Using Local Emulators]]></title>
            <link>https://medium.com/@betomassoni/integrating-gcp-pub-sub-with-kotlin-using-local-emulators-254161ba2f2b?source=rss-3e02c8a08a4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/254161ba2f2b</guid>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Roberto Massoni]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 20:38:52 GMT</pubDate>
            <atom:updated>2024-10-13T20:38:52.221Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Google Cloud Pub/Sub</strong> is a powerful solution for event-driven architectures, allowing asynchronous communication between microservices. However, developing directly in the cloud can be costly and complex. This is where emulators come into play.</p><p><strong>Google Cloud Platform Emulator</strong> refers to a tool that allow developers to simulate GCP services locally. By using emulators, developers can build, test, and debug applications without having to deploy them to the cloud. This is particularly useful in situations where cloud usage may incur costs, or where developers want to ensure their applications are functioning correctly before going live.</p><h3>Advantages of Using Emulators</h3><h4><strong>Cost Reduction</strong>:</h4><ul><li><strong>Avoiding Cloud Charges</strong>: By using emulators, developers can avoid costs associated with cloud services during development and testing. This is especially important for projects with limited budgets or during initial phases where financial resources may be scarce.</li><li><strong>Free Testing</strong>: Emulators allow for comprehensive testing without the need for investment in cloud infrastructure.</li></ul><h4><strong>Performance and Speed</strong>:</h4><ul><li><strong>Faster Execution</strong>: Local emulators generally have quicker response times compared to network calls to cloud services, resulting in a more agile development cycle. This is crucial for efficient development, especially for automated testing.</li><li><strong>Lower Latency</strong>: By eliminating internet communication, network latency is removed, providing a smoother development experience.</li></ul><h4><strong>Offline Development</strong>:</h4><ul><li><strong>Access Without Connection</strong>: Emulators enable developers to work on their projects even when they lack internet access. This is particularly useful in environments with limited connectivity or when cloud access may be intermittent.</li><li><strong>Autonomy in Development</strong>: Working offline provides greater flexibility, allowing developers to focus on their tasks without interruptions.</li></ul><h4><strong>Ease of Testing and Debugging</strong>:</h4><ul><li><strong>Simulating Real Behavior</strong>: Emulators replicate the behavior of cloud services, allowing developers to test their applications in a controlled environment. This results in immediate feedback on code functionality.</li><li><strong>Better Debugging Tools</strong>: Often, development and debugging tools are more accessible and effective in a local environment, enabling developers to track down issues more easily.</li></ul><h4><strong>Ease of setup and maintenance</strong>:</h4><ul><li><strong>Quick Configuration</strong>: Emulators can be rapidly configured using tools like Docker, allowing developers to get their projects up and running efficiently.</li><li><strong>Less Complexity</strong>: Using emulators, teams avoid the complexity of managing credentials and access configurations for cloud services, simplifying the development process.</li></ul><h3>Usage Scenarios for the GCP Emulator</h3><h4><strong>Microservices Development</strong>:</h4><ul><li>In a microservices architecture, the Pub/Sub emulator is ideal for testing communication between services without deploying them to the cloud.</li></ul><h4><strong>Event-Driven Applications</strong>:</h4><ul><li>Developers working on event-driven applications can use the emulator to simulate events and message processing, ensuring that their applications react as expected.</li></ul><h4><strong>Continuous Integration/Continuous Deployment</strong>:</h4><ul><li>Emulators can be integrated into CI/CD pipelines, allowing automated tests to run against the emulator, ensuring that code changes do not break existing functionality.</li></ul><h3>Setting Up the GCP Pub/Sub Emulator with Docker</h3><h4>1. Create a Docker Compose File</h4><p>Create a file named docker-compose.yml with the following content to set up the Pub/Sub emulator:</p><pre>services:<br>  pubsub-emulator:<br>    build:<br>      context: .<br>    ports:<br>      - &quot;8085:8085&quot;</pre><h4>2. Create a Dockerfile</h4><pre># Use the Google Cloud SDK image with emulators<br>FROM google/cloud-sdk:emulators<br><br># Copy the emulator scripts into the container<br>COPY ./emulators /emulators<br><br># Make the scripts executable<br>RUN chmod +x /emulators/*<br><br># Install necessary packages: git and Python 3 with pip<br>RUN apt-get update &amp;&amp; apt-get install -y git python3 python3-pip &amp;&amp; \<br>    pip3 install google-cloud-pubsub<br><br># Set environment variable for the Pub/Sub project ID<br>ENV PUBSUB_PROJECT_ID=some-project<br><br># Start the Pub/Sub emulator and initialize it<br>ENTRYPOINT [&quot;sh&quot;, &quot;-c&quot;, &quot;gcloud beta emulators pubsub start --host-port=0.0.0.0:8085 &amp; sleep 5 &amp;&amp; /emulators/pubsub/init-pubsub.sh&quot;]</pre><h4>3. Create the file to start PubSub inside the container</h4><p>The file <strong>init-pubsub.sh</strong> must be inside the <strong>emulators/pubsub</strong> folder as indicated in the Dockerfile.</p><pre>#!/bin/bash<br><br># Set configuration variables<br>EMULATOR_HOST=&quot;localhost:8085&quot;<br>PROJECT_ID=&quot;some-project&quot;<br>TOPIC_NAME=&quot;some-topic&quot;<br>SUBSCRIPTION_NAME=&quot;some-subscription&quot;<br><br># Export the necessary variables for the script to work<br>export PUBSUB_EMULATOR_HOST=$EMULATOR_HOST<br>export PUBSUB_PROJECT_ID=$PROJECT_ID<br><br># Start the Pub/Sub emulator<br>$(gcloud beta emulators pubsub env-init)<br><br># Wait for the emulator to fully start<br>sleep 5<br><br># Clone the Python Pub/Sub repository<br>git clone https://github.com/googleapis/python-pubsub.git<br><br># Navigate to the samples directory<br>cd python-pubsub/samples/snippets<br><br># Create the topic<br>python3 publisher.py $PROJECT_ID create $TOPIC_NAME<br>echo &quot;Topic &#39;$TOPIC_NAME&#39; created!&quot;<br><br># Create the subscription<br>python3 subscriber.py $PROJECT_ID create $TOPIC_NAME $SUBSCRIPTION_NAME<br>echo &quot;Subscription &#39;$SUBSCRIPTION_NAME&#39; created!&quot;<br><br># Start receiving messages on the subscription<br>python3 subscriber.py $PROJECT_ID receive $SUBSCRIPTION_NAME<br>echo &quot;Listening for messages on &#39;$TOPIC_NAME&#39; with subscription &#39;$SUBSCRIPTION_NAME&#39;...&quot;</pre><h4>4. Create a service to publish a message</h4><pre><br>@Service<br>class PublisherService(private val pubSubProperties: PubSubProperties) {<br><br>    fun publishMessage(message: String) {<br>        val topicName = TopicName.of(pubSubProperties.projectId, pubSubProperties.topicName)<br><br>        var publisher: Publisher? = null<br>        try {<br>            // Create a publisher instance with default settings bound to the topic<br>            publisher = Publisher.newBuilder(topicName).build()<br><br>            val data = ByteString.copyFromUtf8(message)<br>            val pubsubMessage = PubsubMessage.newBuilder().setData(data).build()<br><br>            // Once published, returns a server-assigned message id (unique within the topic)<br>            val messageIdFuture: ApiFuture&lt;String&gt; = publisher.publish(pubsubMessage)<br>            val messageId = messageIdFuture.get()<br>            println(&quot;Published message ID: $messageId&quot;)<br>        } finally {<br>            if (publisher != null) {<br>                // When finished with the publisher, shutdown to free up resources.<br>                publisher.shutdown()<br>                publisher.awaitTermination(1, TimeUnit.MINUTES)<br>            }<br>        }<br>    }<br>}</pre><h4>5. Create a service to receive a message</h4><pre><br>@Service<br>class SubscriberService(<br>    private val pubSubProperties: PubSubProperties,<br>) {<br>    private val receivedMessages = mutableListOf&lt;String&gt;()<br><br>    fun receiveMessages(): List&lt;String&gt; {<br>        val subscriptionName = ProjectSubscriptionName.of(pubSubProperties.projectId, pubSubProperties.subscriptionName)<br><br>        // Instantiate an asynchronous message receiver.<br>        val receiver =<br>            MessageReceiver { message: PubsubMessage, consumer -&gt;<br>                receivedMessages.add(&quot;Id: ${message.messageId}, Data: ${message.data.toStringUtf8()}&quot;)<br>                consumer.ack()<br>            }<br><br>        var subscriber: Subscriber? = null<br>        try {<br>            subscriber = Subscriber.newBuilder(subscriptionName, receiver).build()<br>            // Start the subscriber.<br>            subscriber.startAsync().awaitRunning()<br>           <br>            // Allow the subscriber to run for 30s unless an unrecoverable error occurs.<br>            subscriber.awaitTerminated(30, TimeUnit.SECONDS)<br>        } catch (timeoutException: TimeoutException) {<br>            // Shut down the subscriber after 30s. Stop receiving messages.<br>            subscriber?.stopAsync()<br>        }<br><br>        return receivedMessages.toList()<br>    }<br>}</pre><h4>6. Create a endpoint to send/receive messages</h4><pre><br>@RestController<br>@RequestMapping(&quot;/api/pubsub&quot;)<br>class MessageController(<br>    private val publisherService: PublisherService,<br>    private val subscriberService: SubscriberService<br>) {<br>    @PostMapping(&quot;/publish&quot;)<br>    fun publishMessage(<br>        @RequestBody message: String,<br>    ): ResponseEntity&lt;Any&gt; {<br>        publisherService.publishMessage(message)<br>        return ResponseEntity.ok(&quot;Message published successfully.&quot;)<br>    }<br><br>    @GetMapping(&quot;/receive&quot;)<br>    fun receiveMessages(): ResponseEntity&lt;Any&gt; {<br>        val messages = subscriberService.receiveMessages()<br>        return ResponseEntity.ok(messages)<br>    }<br>}</pre><p>At this moment, the container simulating the Google service should be running and the API will be ready to send messages to the created topic, and the subscriber will be able to receive messages.</p><h3>AWS Alternative: LocalStack</h3><p>If you work with AWS, there is an alternative called <a href="https://localstack.com/">LocalStack</a>, which simulates AWS services locally, such as SQS, which is equivalent to Pub/Sub.</p><h4><strong>Basic LocalStack Setup in Docker:</strong></h4><pre>services:<br>  localstack:<br>    image: localstack/localstack<br>    ports:<br>      - &quot;4566:4566&quot;<br>    environment:<br>      - SERVICES=sqs</pre><h3>Conclusion</h3><p>The <strong>GCP emulator</strong>, especially the <strong>Pub/Sub emulator</strong>, is a powerful tool for developers looking to build, test, and refine their applications without the overhead of deploying to the cloud. By leveraging emulators, teams can improve their development workflows, <strong>reduce costs</strong>, and ensure their applications are robust and ready for production.</p><p>If you want to see a complete example of integrating the GCP Pub/Sub emulator with a Kotlin application and Spring, check out my GitHub repository:</p><p><a href="https://github.com/betomassoni/pubsub-emulator-example">GitHub - betomassoni/pubsub-emulator-example</a></p><h4>References used in this post</h4><ul><li><a href="https://cloud.google.com/pubsub/docs/publish-receive-messages-client-library">Quickstart: Publish and receive messages in Pub/Sub by using a client library | Pub/Sub Documentation | Google Cloud</a></li><li><a href="https://cloud.google.com/pubsub/docs/emulator">Testing apps locally with the emulator | Pub/Sub | Google Cloud</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=254161ba2f2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS SQS em 4 passos simples com JMS e Spring Boot + Bônus]]></title>
            <link>https://medium.com/@betomassoni/aws-sqs-simples-com-jms-e-spring-boot-ce30447762e2?source=rss-3e02c8a08a4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce30447762e2</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[jms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[aws-sqs]]></category>
            <dc:creator><![CDATA[Roberto Massoni]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 04:26:03 GMT</pubDate>
            <atom:updated>2021-09-07T23:54:28.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCadGtUbU0E2TNYGfu9Arg.jpeg" /></figure><h3>O que é o AWS SQS?</h3><p>O Amazon SQS ou <em>Simple Queue Service</em> é um serviço que nos permite trabalhar utilizando mensageria, o que possibilita a comunicação entre dois sistemas por meio de mensagens. Por sua vez, essas mensagens são enviadas para uma fila e, então, processadas assim que estiverem disponíveis.</p><p>Segundo a <a href="https://docs.aws.amazon.com/pt_br/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html">documentação</a> da AWS:</p><p><em>“O Amazon Simple Queue Service (Amazon SQS) oferece uma fila hospedada segura, durável e disponível que permite integrar e desacoplar sistemas de software e componentes distribuídos”.</em></p><h3>Entendi, mas para que é utilizado?</h3><p>Em uma comunicação tradicional entre sistemas como HTTP, Rest ou SOAP, os endpoints devem estar funcionando no momento em que ocorre tal interação. Se um deles estiver com o servidor indisponível, provavelmente a tarefa em questão falhará. Para que dois sistemas se comuniquem, ambos devem estar funcionando em plena capacidade.</p><p>Utilizar mensageria significa que um sistema A pode enviar uma mensagem para o sistema B, o qual fará a leitura dessa mensagem assim que possível. É importante ressaltar que isso não necessariamente acontecerá no exato momento da entrega.</p><p>Abstraindo para o mundo real, poderíamos enviar uma carta para um destinatário e este não necessariamente precisaria estar presente em sua casa para receber a mensagem. Caso ele estivesse ausente, assim que ele chegasse, poderia checar suas correspondências e encontraria nossa mensagem, ou seja, essa comunicação seria assíncrona. Curiosamente podemos observar nesse exemplo que a caixa de correio do destinatário desempenha um dos papéis do SQS: <strong>receber mensagens e disponibilizá-las para um destinatário de forma segura assim que este estiver disponível</strong>.</p><h3>E o que é o JMS?</h3><p>O <em>Java Message Service</em> ou JMS é uma biblioteca JAVA que permite a utilização do AWS SQS como provedor com <strong>poucas linhas de código</strong>. A partir dela, podemos criar produtores para enviar mensagens para uma fila, assim como consumidores que possam receber uma mensagem em uma fila SQS.</p><h3>Passo #1 — Criando uma fila na AWS e credenciais de acesso</h3><p>É claro que esse serviço fornecido pela AWS é pago e é possível ter uma estimativa de custo através da própria <a href="https://calculator.aws/#/createCalculator/SQS">calculadora da AWS</a>. No entanto, você também pode criar uma conta <a href="https://aws.amazon.com/pt/free/">Free Tier</a> e conseguir <strong>12 meses gratuitos</strong> em muitos serviços, inclusive o SQS.</p><p>Com sua conta AWS criada, acesse o console, entre no serviço <em>Simple Queue Service, </em>clique no botão <em>criar fila</em> e escolha um nome para sua fila:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6Itfwb3fSTlpIkcz0lH6A.png" /></figure><p>Confirme novamente no final da página no botão <em>criar fila</em>.</p><p>Nesse momento, a sua fila de mensagens já está criada, mas ainda é preciso das credenciais para que sua aplicação consiga acessar a sua conta AWS. E para isso, você pode acessar a opção <strong>IAM</strong> no console e criar um usuário que tenha a permissão para acessar sua fila (na <a href="https://docs.aws.amazon.com/pt_br/IAM/latest/UserGuide/id_credentials_access-keys.html">documentação</a> você terá mais detalhes deste passo se precisar). <strong>Após criar o usuário, você deve fazer o download do arquivo no qual consta a sua <em>secret key</em> e <em>access key</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*ouIQI2te_4dM0kC_qEzZ4g.png" /></figure><h3>Passo #2 — Criando uma mensagem na fila</h3><p>O produtor de mensagens poderia ser uma aplicação, um SNS, um Lambda, AWS CLI ou até mesmo pelo console da AWS (que é a forma mais rápida para fazermos o teste).</p><p>Dessa forma, ainda na AWS, selecionamos a fila criada, clicamos no botão <em>Enviar e receber mensagens</em>, preenchemos no campo<em> Corpo da mensagem </em>a nossa mensagem e finalizamos clicando no botão<em> Enviar mensagem.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*m42Om5A4GHE7Z9PEV9keCA.png" /></figure><p>A mensagem “Teste de Mensagem” entrará para a fila para aguardar a leitura por algum <em>consumer</em>.</p><h3><strong>Passo #3 — Configurando a aplicação</strong></h3><p>Para esta implementação, primeiro é necessário definir todas as dependências que seu projeto Spring terá. Abaixo estão todas elas e você deve adicionar no arquivo <em>build.gradle </em>do projeto:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27d8716bed9d287478712756e1c0e030/href">https://medium.com/media/27d8716bed9d287478712756e1c0e030/href</a></iframe><ul><li><strong>aws-java-sdk-sqs</strong>: responsável por estabelecer o cliente do SQS</li><li><strong>amazon-sqs-java-messaging-lib</strong>: responsável por interagir com o JMS</li><li><strong>spring-jms</strong>: permite utilizar o JMS com o Spring</li></ul><p>No arquivo <em>application.properties</em> devemos informar os dados da nossa fila criada, bem como as credenciais de acesso (obtidas nos passos anteriores ao fazer o download do arquivo) e a região da nossa máquina na AWS:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3db3090c40f46a627b28bda51008da9/href">https://medium.com/media/e3db3090c40f46a627b28bda51008da9/href</a></iframe><p>O terceiro passo é realizar a configuração do JMS:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e557d3cf9f088266d36bd0719cd17930/href">https://medium.com/media/e557d3cf9f088266d36bd0719cd17930/href</a></iframe><p>Note que na linha #17 foi necessário colocar uma anotação para ativar o JMS no contexto do projeto. As variáveis membros são utilizadas para obter o valor configurado no arquivo <em>application.properties</em>. Já os dois métodos criados, <em>connectionFactorySqs</em> e <em>jmsListenerContainerFactory</em>, servem para criar uma factory de conexões do SQS utilizando os dados injetados (região e credenciais) e para configurar o JMS para receber o <em>factory</em> de conexões, respectivamente.</p><p>Outro ponto importante é que na linha #34 está sendo informado o secretKey e accessKey, logo, essas configurações precisariam estar configuradas corretamente no arquivo <em>application.properties</em> e esta não é uma boa prática, já que são dados sensíveis. Por isso, também podemos utilizá-los de outra forma alterando essa linha para:</p><pre>.withCredentials(new DefaultAWSCredentialsProviderChain())</pre><p>A partir disso, você poderá utilizar as variáveis de ambiente AWS_ACCESS_KEY e AWS_SECRET_KEY em vez de de expor suas credenciais na aplicação.</p><h3>Passo #4 — Finalmente, o consumer com JMS</h3><p>Feitas essas configurações, a única parte restante do código para que nossa mensageria funcione é o consumidor JMS, o qual será responsável por receber as mensagens. Para isso, precisamos criar a classe EventConsumer.java e anotá-la com o @Service do Spring.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3512dc32228c3735951c949b467a0fba/href">https://medium.com/media/3512dc32228c3735951c949b467a0fba/href</a></iframe><p>A anotação <em>JmsListener</em> no método é necessária para que o JMS &quot;ouça&quot; sua fila e verifique se ali há novas mensagens para serem lidas ou não. Para isso, precisamos informar o nome da fila no atributo <em>destination</em> (que no caso está sendo recuperada via propriedade).</p><p>É muito importante ressaltar a necessidade de introduzir um <em>try catch</em> nesse código com um lançamento de exceção. Através desse trecho de código o JMS é capaz de fazer um tratamento de erro e devolver a mensagem (que tentou receber mas por algum motivo ocorreu uma exceção) à fila SQS. <strong>Isso é primordial para que JMS garanta que todas as mensagens recebidas serão processadas com sucesso na aplicação.</strong></p><p>E pronto! Nesse exato momento, a nossa aplicação será capaz de identificar que uma nova mensagem foi colocada na fila e o método <em>receiveEvent</em> irá obtê-la.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0podFY1uIVxoOg3lV38DA.png" /></figure><h3>Conclusão</h3><p>É claro que no exemplo foi colocado um texto qualquer, mas o produtor poderia ser um JSON, um XML, etc., por exemplo, e a aplicação poderia fazer o necessário com esse dado.</p><p>Ainda que pareça um tanto complicado, a documentação da AWS é bem completa e nos possibilita a ter muitas alternativas diferentes para implementação, o JMS é só mais uma e a que eu já utilizei. Além disso, ainda há uma infinidade de configurações que você pode realizar para que sua fila trabalhe de acordo com sua necessidade, por exemplo, delay para recebimento/entrega de mensagens, tipos de filas FIFO ou padrão, temporizadores de mensagens, tempo de espera enquanto a mensagem está sendo processada e muitas outras.</p><p>Um dos maiores desafios das empresas no cenário atual é trabalhar com microsserviços e o recurso de mensageria se torna essencial para que tenhamos sistemas confiáveis, tolerante a falhas e de alto desempenho.</p><p>Esse é um exemplo simples e fácil de construir se seguir todos esses passos mas que pode ser incrementado conforme a sua necessidade.</p><h3>Dica bônus: LocalStack, uma alternativa para o dev</h3><p>Em muitos cenários, o desenvolvedor não tem acesso a AWS ou simplesmente precisa utilizar um serviço mock por questões de performance ou acesso. E para isso também há uma solução: LocalStack.</p><p>O LocalStack é uma imagem para o Docker na qual você consegue simular os serviços da AWS, inclusive o SQS, de forma muito simples. Basta iniciar um contêiner com essa imagem e apontar sua configuração local da sua aplicação para o endereço e porta criado pelo contêiner.</p><p><a href="https://github.com/localstack/localstack">GitHub - localstack/localstack: 💻 A fully functional local AWS cloud stack. Develop and test your cloud &amp; Serverless apps offline</a></p><h3>Demo</h3><p>Disponibilizei um exemplo completo no meu GitHub:</p><p><a href="https://github.com/betomassoni/sqs-jms-spring-example">https://github.com/betomassoni/sqs-jms-spring-example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce30447762e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>